🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Iterate Through a List in Python
How to Iterate Through a List in Python – Complete Guide
TLDR: You can iterate through a Python list using for loops, list comprehensions, while loops with index, enumerate(), map(), and even the iter()/next() combo. Each approach fits a different scenario. This guide covers all of them with runnable code examples.
Introduction
If you have worked with Python for more than a week, you have a list. If you have a list, at some point you need to walk through every element in it. That is iteration, and Python gives you a surprising number of ways to do it.
Most tutorials throw one for item in list: example at you and call it done. That is the right starting point, but it barely scratches the surface. Python’s iteration model is one of its most elegant features. Once you understand the full toolkit, you will write cleaner, faster code without even thinking about it.
In this tutorial, you will learn every practical way to iterate through a list in Python. We will start with the basics and move into advanced patterns. Every example is runnable as-is.
1. The Basic For Loop
The most common approach is the simplest one.
fruits = ["apple", "banana", "cherry", "mango"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
mango
Python’s for loop iterates directly over the values. There is no need to manage an index variable or call .get() on anything. The language takes care of the mechanics.
This pattern works for any iterable: lists, tuples, strings, sets, dictionaries. The syntax stays the same.
The fact that Python treats all these types uniformly is not accidental. Under the hood, they all implement the iterator protocol. Knowing how that protocol works gives you a deeper understanding of why Python iteration behaves the way it does, and it lets you build your own iterables that slot right into for loops alongside built-in types.
2. Iterating With Index Using range()
Sometimes you need the index alongside the value. The range() function generates a sequence of numbers that you can use as positions.
colors = ["red", "green", "blue", "yellow"]
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")
Output:
Index 0: red
Index 1: green
Index 2: blue
Index 3: yellow
len(colors) gives you 4. range(4) generates 0, 1, 2, 3. You then use that index to access the list.
This pattern is verbose compared to the direct for loop. Use it only when you genuinely need the index. If you only need the values, use the basic for loop instead.
3. Using enumerate()
enumerate() is the Pythonic way to get both index and value in a single pass. It returns a tuple for each element: (index, value).
cities = ["Mumbai", "Delhi", "Bangalore", "Chennai"]
for index, city in enumerate(cities):
print(f"{index} -> {city}")
Output:
0 -> Mumbai
1 -> Delhi
2 -> Bangalore
3 -> Chennai
enumerate() is cleaner than range(len(...)) and it is the preferred approach whenever you need the index. You can also start the index from 1 instead of 0 by passing a second argument:
for pos, city in enumerate(cities, start=1):
print(f"{pos}. {city}")
Output:
1. Mumbai
2. Delhi
3. Bangalore
4. Chennai
4. List Comprehension
A list comprehension is a compact way to build a new list by iterating over an existing one. It is not strictly iteration, but it is the Pythonic one-liner that replaces a full loop when your goal is to transform or filter data.
numbers = [1, 2, 3, 4, 5]
squares = [n ** 2 for n in numbers]
print(squares)
Output:
[1, 4, 9, 16, 25]
You can also add a condition to filter:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
print(even_squares)
Output:
[4, 16, 36, 64, 100]
List comprehensions are faster than traditional loops in Python because they are optimized at the interpreter level. Use them when you are building a new list from an existing one.
5. Using a While Loop
Python supports the traditional while loop with an explicit index counter. This gives you full control over the iteration process, including the ability to skip elements or break early based on conditions.
stack = ["first", "second", "third", "fourth"]
i = 0
while i < len(stack):
print(f"Processing: {stack[i]}")
i += 1
Output:
Processing: first
Processing: second
Processing: third
Processing: fourth
while loops with an index are less common in Python than in languages like C or Java. The for loop covers most use cases cleanly. Use while when you have a condition that is not just “iterate over everything.”
6. Iterating in Reverse
Python makes it simple to iterate backwards through a list using reversed().
letters = ["a", "b", "c", "d", "e"]
for letter in reversed(letters):
print(letter)
Output:
e
d
c
b
a
reversed() does not modify the original list. It returns an iterator that yields elements in reverse order. You can also combine it with enumerate():
for i, letter in enumerate(reversed(letters)):
print(f"{len(letters) - i - 1}: {letter}")
7. Iterating With a Step Using range()
When you need to skip elements as you iterate, range() with a step argument is the tool.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Every second element
for n in range(0, len(numbers), 2):
print(numbers[n])
Output:
0
2
4
6
8
The three arguments to range() are: start, stop, and step. range(0, 10, 2) generates 0, 2, 4, 6, 8. You then use those indices to access the list.
8. Using map()
map() applies a function to every element in an iterable and returns an iterator with the results.
temperatures = [0, 20, 37, 100]
celsius_to_fahrenheit = lambda t: (t * 9/5) + 32
results = list(map(celsius_to_fahrenheit, temperatures))
print(results)
Output:
[32.0, 68.0, 98.6, 212.0]
map() is lazy, meaning it does not compute until you consume it. Wrapping it in list() forces evaluation. This pattern is useful when you want to apply a transformation without writing an explicit loop.
9. Using iter() and next()
Python’s iter() function returns an iterator object from any iterable. You can then call next() repeatedly to get each element.
animals = ["cat", "dog", "rabbit", "hamster"]
animal_iterator = iter(animals)
print(next(animal_iterator)) # cat
print(next(animal_iterator)) # dog
print(next(animal_iterator)) # rabbit
print(next(animal_iterator)) # hamster
Output:
cat
dog
rabbit
hamster
Calling next() past the last element raises a StopIteration exception. You can catch it or use it with a for loop implicitly. This low-level approach is rarely needed for simple list iteration, but it is the foundation that powers all of Python’s iteration protocols.
10. Iterating Over Multiple Lists With zip()
When you have two or more lists and need to iterate over them together, zip() pairs them up element by element.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output:
Alice: 85
Bob: 92
Charlie: 78
If the lists are different lengths, zip() stops at the shorter one. If you want to process all elements regardless of length, use itertools.zip_longest().
11. Iterating Over a Slice of a List
You can iterate over a portion of a list using slice notation inside the for loop.
data = [10, 20, 30, 40, 50, 60, 70, 80]
# Skip first two, iterate through the rest
for val in data[2:]:
print(val)
Output:
30
40
50
60
70
80
Slice notation is list[start:stop:step]. data[2:] means “from index 2 to the end.” You can combine slices with step:
# Every second element starting from index 1
for val in data[1::2]:
print(val)
Output:
20
40
60
80
12. Iterating With Conditional Logic (Early Break)
Sometimes you do not need to iterate through the entire list. You want to find the first match and stop.
products = [{"name": "laptop", "price": 999},
{"name": "phone", "price": 699},
{"name": "tablet", "price": 449},
{"name": "monitor", "price": 299}]
budget = 500
for product in products:
if product["price"] <= budget:
print(f"Found within budget: {product['name']} at ${product['price']}")
break
Output:
Found within budget: tablet at $449
The break statement stops the loop as soon as the condition is met. Without break, Python would check every product even after finding one within budget.
13. Using iter() With a Sentinel Value
iter() can take a second argument that acts as a sentinel. The iterator stops when the callable returns this sentinel value.
def read_chunks():
return ["chunk1", "chunk2", "chunk3", "END", "should not appear"]
data_stream = iter(read_chunks())
for chunk in iter(lambda: next(data_stream), "END"):
print(chunk)
Output:
chunk1
chunk2
chunk3
This pattern is less common but powerful for processing data streams or reading files with known terminators.
14. Practical Example: Aggregating Data From a List of Dictionaries
Iteration becomes powerful when you combine it with built-in functions. Here is a realistic example that iterates through a list of dictionaries to compute aggregate statistics.
employees = [
{"name": "Ravi", "department": "Engineering", "salary": 85000},
{"name": "Priya", "department": "Marketing", "salary": 72000},
{"name": "Amit", "department": "Engineering", "salary": 91000},
{"name": "Sneha", "department": "Marketing", "salary": 68000},
{"name": "Vikram", "department": "Engineering", "salary": 88000},
]
# Group salaries by department
dept_salaries = {}
for emp in employees:
dept = emp["department"]
salary = emp["salary"]
if dept not in dept_salaries:
dept_salaries[dept] = []
dept_salaries[dept].append(salary)
# Compute average salary per department
for dept, salaries in dept_salaries.items():
avg = sum(salaries) / len(salaries)
print(f"{dept}: avg salary = {avg:.2f}")
Output:
Engineering: avg salary = 88000.00
Marketing: avg salary = 70000.00
This kind of grouping and aggregation is a daily task in data processing. The pattern of iterating once and building intermediate data structures is far more efficient than making multiple passes over the data.
15. List Iteration Gotchas and How to Avoid Them
Understanding a few Python quirks will save you from frustrating bugs.
Modifying a List While Iterating
Never modify a list you are iterating over. The behavior is unpredictable.
nums = [1, 2, 3, 4, 5]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
This might silently skip elements because the iterator’s internal pointer gets out of sync with the list length after each deletion. Instead, iterate over a copy:
nums = [1, 2, 3, 4, 5]
for n in nums[:]: # creates a shallow copy of the list
if n % 2 == 0:
nums.remove(n)
print(nums)
Output:
[1, 3, 5]
List vs Iterator: Single vs Multiple Passes
A list is a sequence you can loop over multiple times. An iterator yields items on demand and is exhausted after one pass.
numbers = [1, 2, 3]
iter_numbers = iter(numbers)
for n in iter_numbers:
print(n)
# Second pass - nothing happens because the iterator is exhausted
for n in iter_numbers:
print(n) # Nothing printed
If you need multiple passes, use the original list or convert the iterator to a list first with list(iter()).
Iterator Inefficiency With len() in range()
When you use range(len(lst)), Python evaluates len(lst) once at the start. That is fine for lists. But if your list changes size during the loop (which you should avoid per the previous point), the loop bounds are fixed and you will get an index error. This is one more reason to prefer direct iteration when possible.
Comparison Table: When to Use What
| Method | Best For |
for item in list |
Simple iteration over all values |
range(len(...)) |
When you need the index but not enumerate |
enumerate() |
Index + value together |
| List comprehension | Transforming or filtering into a new list |
while loop |
Complex exit conditions |
reversed() |
Backward iteration |
range(start, stop, step) |
Skipping elements with a fixed step |
map() |
Applying a function to all elements |
zip() |
Iterating over multiple lists together |
Slice list[start:stop:step] |
Iterating over a subset of a list |
iter() + next() |
Low-level iterator control |
FAQ
Q: Which list iteration method is fastest in Python?
A: In most cases, the difference is negligible for small to medium lists. List comprehensions are slightly faster than explicit for loops when building a new list because the interpreter optimizes them. For simple iteration without building a new list, for item in lst is the fastest in terms of readability and performance. Profile your specific use case if performance is critical.
Q: Can I iterate through a list of dictionaries in Python?
A: Yes. The pattern is the same as iterating through any list. Each dictionary is an element.
users = [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]
for user in users:
print(user["name"], user["age"])
Q: How do I skip the first element of a list during iteration?
A: Use slice notation list[1:] or start enumerate() from index 1 with enumerate(lst, start=1). Both approaches work cleanly and avoid the overhead of managing an index counter manually.
Q: What is the difference between iter() and enumerate()?
A: iter() returns an iterator object. enumerate() returns an enumerate object that yields (index, value) tuples. You use enumerate() when you need both index and value in a single loop. You use iter() when you want low-level control over the iteration process or are working with custom iterables.
Q: How do I iterate through two lists of different lengths?
A: Use zip() if you want to stop at the shorter list. Use itertools.zip_longest() if you want to process all elements and fill missing values with a default.
from itertools import zip_longest
a = [1, 2, 3]
b = ["x", "y"]
for num, letter in zip_longest(a, b, fillvalue="N/A"):
print(num, letter)
Q: Is it possible to iterate through a list of lists?
A: Yes. Each element is itself a list, so you get the inner list on each iteration. You can then iterate through that inner list if needed.
matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
for val in row:
print(val, end=" ")
print()
Q: Does Python support parallel iteration like threads?
A: Python’s Global Interpreter Lock (GIL) means threads do not provide true parallel execution for CPU-bound tasks. For I/O-bound iteration, consider asyncio or concurrent.futures.ThreadPoolExecutor. For CPU-bound parallel iteration, multiprocessing or concurrent.futures.ProcessPoolExecutor provides actual parallelism.
Conclusion
Python gives you more iteration tools than most developers ever use. The for item in list: loop is the foundation, but enumerate(), zip(), list comprehensions, and map() exist for good reasons. The right tool depends on what you need from the iteration.
Master these patterns and your code will get shorter and clearer. Iteration is one of those skills that separates developers who fight Python from those who work with it.
