Python Loop Lists
Looping lets you visit every item in a list one by one, and Python offers several styles depending on whether you also need the index.
Looping with a for loop
The simplest way to walk through a list is a for loop, which hands you each item in turn without you having to track positions. This is the most readable choice when you only need the values themselves.
Basic for loop
cities = ["Paris", "Tokyo", "Cairo"]
for city in cities:
print(city)This prints each city on its own line. The variable city takes the value of each item in order, from the first to the last.
Looping with an index
When you also need the position of each item, enumerate() is the cleanest option. It yields both the index and the value on every pass, so you avoid manually managing a counter.
enumerate() for index and value
cities = ["Paris", "Tokyo", "Cairo"]
for index, city in enumerate(cities):
print(index, city)The output pairs each position with its value: 0 Paris, 1 Tokyo, 2 Cairo. You can also start counting from another number with enumerate(cities, start=1).
Other looping styles
- range(len(list)): loop over index numbers when you need to modify items in place.
- while loop: repeat with a manual counter that you increment yourself.
- List comprehension: a compact one-line loop that builds a new list.
Looping with a while loop
cities = ["Paris", "Tokyo", "Cairo"]
i = 0
while i < len(cities):
print(cities[i])
i += 1