Loop Lists
Learn how to loop through Python lists using for loops, while loops, enumerate(), zip(), break, continue, and list comprehensions with examples.
Looping through a list — visiting each item one by one — is one of the most common operations in Python. This chapter covers every practical way to do it: for loops, while loops, enumerate(), zip(), break and continue, and list comprehensions. It also explains the gotchas to watch out for when modifying a list while iterating.
Why Loop Through a List?
A Python list holds an ordered sequence of items. Loops let you act on every item without writing one line of code per item. Whether you are summing prices, filtering records, or transforming strings, a loop is usually the right tool.
Looping with a for Loop
The simplest and most readable way to iterate over a list is a for loop.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)apple
banana
cherryPython assigns each item to fruit in turn, executes the indented block, then moves to the next item. The loop stops automatically when the list is exhausted — no index management required.
Looping with range() and an Index
When you need both the index and the value, you can combine range() with len():
colors = ['red', 'green', 'blue']
for i in range(len(colors)):
print(i, colors[i])0 red
1 green
2 blueThis works, but enumerate() (covered next) is cleaner for this pattern.
Looping with enumerate()
enumerate() pairs each item with its index and is the idiomatic Python approach when you need both:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)0 apple
1 banana
2 cherryYou can start the counter at a different number by passing a second argument:
for index, fruit in enumerate(['apple', 'banana', 'cherry'], start=1):
print(index, fruit)1 apple
2 banana
3 cherryLooping Over Two Lists with zip()
zip() pairs items from two (or more) lists together so you can iterate them side by side:
names = ['Alice', 'Bob', 'Carol']
scores = [92, 85, 78]
for name, score in zip(names, scores):
print(name, '->', score)Alice -> 92
Bob -> 85
Carol -> 78If the lists have different lengths, zip() stops at the shorter one. Use itertools.zip_longest() if you need to continue to the end of the longer list.
Looping with a while Loop
A while loop keeps running as long as a condition is True. You manage the index yourself:
numbers = [10, 20, 30, 40, 50]
i = 0
while i < len(numbers):
print(numbers[i])
i += 110
20
30
40
50while loops are useful when the stopping condition is not simply "end of list" — for example, searching for an item and stopping as soon as it is found.
Controlling Loop Execution
break — Exit Early
break stops the loop immediately. This is useful when you have found what you were looking for and do not need to keep iterating:
fruits = ['apple', 'banana', 'cherry', 'date']
for fruit in fruits:
if fruit == 'cherry':
print('Found it!')
break
print(fruit)apple
banana
Found it!continue — Skip an Item
continue jumps to the next iteration without executing the remaining lines in the current block:
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 == 0:
continue # skip even numbers
print(n)1
3
5The else Clause on a Loop
A for or while loop can have an else block that runs when the loop finishes without hitting a break. This is handy for "search and report" patterns:
target = 7
numbers = [1, 3, 5, 9]
for n in numbers:
if n == target:
print('Found', target)
break
else:
print(target, 'not in list')7 not in listLooping Over a List Slice
You can iterate over part of a list by slicing it:
items = ['a', 'b', 'c', 'd', 'e']
for item in items[1:4]: # indices 1, 2, 3
print(item)b
c
dLooping in reverse with a slice:
for item in items[::-1]:
print(item)e
d
c
b
aNested Loops
You can nest for loops to work with lists of lists or to compute combinations:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
for row in matrix:
for value in row:
print(value, end=' ')
print()1 2 3
4 5 6
7 8 9 The inner loop completes all its iterations for every single iteration of the outer loop.
List Comprehensions as a Loop Alternative
A list comprehension creates a new list by applying an expression to every item — it is a compact, readable alternative to a for loop that builds a list:
numbers = [1, 2, 3, 4, 5]
# for loop approach
squares = []
for n in numbers:
squares.append(n ** 2)
# list comprehension — same result in one line
squares = [n ** 2 for n in numbers]
print(squares)[1, 4, 9, 16, 25]You can add a condition to filter items at the same time:
evens = [n for n in range(1, 11) if n % 2 == 0]
print(evens)[2, 4, 6, 8, 10]Common Gotcha: Modifying a List While Iterating
Do not add or remove items from a list inside a for loop that iterates over that same list. The loop's internal index is based on the original length, so items can be skipped or visited twice.
# BAD — skips items
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
numbers.remove(n) # mutates the list mid-loop
print(numbers) # [1, 3, 5] may look correct here but...The safe pattern is to iterate over a copy of the list, or build a new list with a comprehension:
numbers = [1, 2, 3, 4, 5]
numbers = [n for n in numbers if n % 2 != 0]
print(numbers)[1, 3, 5]Basic List Operations Used with Loops
The sections below recap the list methods most often used alongside loops. See Python List Methods for the full reference.
Append Elements
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)[1, 2, 3, 4]Remove Elements
remove() deletes the first matching value and raises a ValueError if the item is not found.
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list)[1, 2, 4, 5]Sort a List
my_list = [3, 1, 4, 2, 5]
my_list.sort()
print(my_list)[1, 2, 3, 4, 5]sort() modifies the list in place. To get a sorted copy without changing the original, use the built-in sorted() function. See Sort Lists for sorting in reverse, sorting by key, and more.
Related Topics
- Python Lists — creating, indexing, and slicing lists
- Python for Loops — the full
forloop reference - Python while Loops —
whileloop syntax and patterns - List Comprehension — compact one-line list building
- List Methods —
append,extend,pop,insert, and more - Sort Lists — sorting in place vs. sorted copies
- Remove List Items —
remove,pop,del, andclear - Loop Dictionaries — iterating over key–value pairs
- Loop Tuples — iterating over immutable sequences