Home »
Python
Python - Loop Through a List
Last Updated : May 01, 2025
In Python, looping through a list lets you access and process each item one by one. This is commonly done using a for
loop, but can also be done using other approaches. In this chapter, we will learn all possible methods to loop through a list (iterating over list elements) with the help of examples.
Looping Through a List Using a for Loop
The for
loop is the most common and straightforward way to iterate through a list in Python. It goes through each item in the list one by one.
Example
In this example, we are looping through a list of cities using a for
loop and printing each city name.
# Creating a list of cities
cities = ["New York", "London", "Paris", "Berlin"]
# Looping through the list
for city in cities:
print(city)
The output of the above code would be:
New York
London
Paris
Berlin
Looping Through a List Using for Loop with Index
You can use the range()
function with len()
to loop through list items by index. This approach is useful when you need both the index and the value.
Example
In this example, we are printing each city name along with its index.
# Creating a list of cities
cities = ["New York", "London", "Paris", "Berlin"]
# Looping through the list using index
for i in range(len(cities)):
print(f"Index {i}: {cities[i]}")
The output of the above code would be:
Index 0: New York
Index 1: London
Index 2: Paris
Index 3: Berlin
Looping Through a List Using while Loop
You can also loop through a list using a while
loop. This gives more control over the iteration but requires manual management of the index.
Example
In this example, we are using a while
loop to iterate through a list of cities.
# Creating a list of cities
cities = ["New York", "London", "Paris", "Berlin"]
# Using while loop to iterate
i = 0
while i < len(cities):
print(cities[i])
i += 1
The output of the above code would be:
New York
London
Paris
Berlin
Looping Through a List Using List Comprehension
List comprehensions provide a concise way to loop through a list and apply an operation to each item.
Example
In this example, we are printing each city name using a list comprehension.
# Creating a list of cities
cities = ["New York", "London", "Paris", "Berlin"]
# Looping using list comprehension
[print(city) for city in cities]
The output of the above code would be:
New York
London
Paris
Berlin
Exercise
Select the correct option to complete each statement about looping through a Python list.
- Which keyword is commonly used to iterate over a list in Python?
- What will the following code print?
for item in [1, 2, 3]: print(item)
- Which function can be used with
for
to get both index and value while looping?
Advertisement
Advertisement