PythonPandas.com

Iterate over a list in Python



In this article, you’ll learn different methods to iterate over lists, from basic for loops to advanced tools like enumerate(), zip(), and list comprehensions.

Method 1: Using a Simple for Loop (Most Common)

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
print(fruit)

Output:

 apple banana cherry

This method automatically handles variable-length lists.

Method 2: Using range() and Indexing

You can iterate through a list by index if you need access to both position and value.

fruits = ['apple', 'banana', 'cherry']

for i in range(len(fruits)):
print(i, fruits[i])

Output:

 0 apple 1 banana 2 cherry

This method is Useful when you need both index and element. It allows direct modification of list items by index.

Method 3: Using enumerate() (Best for Index + Value)

enumerate() is the most Pythonic way to get both index and value in a loop.

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
print(f”Index {index}: {fruit}”)

Output:

 Index 0: apple Index 1: banana Index 2: cherry

Method 4: Using while Loop

Though less common, you can iterate using a while loop.

fruits = ['apple', 'banana', 'cherry'] i = 0

while i < len(fruits):
print(fruits[i])
i += 1

Output:

 apple banana cherry

This method is Useful when you need conditional looping or manual control

Method 5: Using list comprehension (Compact Syntax)

List comprehensions are concise one-liners for looping and creating new lists.

fruits = ['apple', 'banana', 'cherry']
# Print each item
[print(fruit) for fruit in fruits]

Output:

 apple banana cherry

Method 6: Using zip() to Loop Through Multiple Lists

When you want to iterate over two or more lists simultaneously:


names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
print(f”{name} is {age} years old”)

Output:

 Alice is 25 years old 
Bob is 30 years old 
Charlie is 35 years old

Why use this?
> Perfect for pairing related lists together
> Automatically stops at the shortest list length

Method 7: Using enumerate() + zip() Together

You can combine both for advanced looping with index tracking.


names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 92]

for i, (name, score) in enumerate(zip(names, scores), start=1):
print(f”{i}. {name} scored {score}”)

Output:

 1. Alice scored 90 
2. Bob scored 85 
3. Charlie scored 92

This method is useful for creating ranked or indexed reports.

Method 8: Iterating in Reverse Order

Use reversed() to iterate backward through a list.

fruits = ['apple', 'banana', 'cherry']

for fruit in reversed(fruits):
print(fruit)

Output:

 cherry banana apple

Why use this?
> Simple and memory-efficient way to reverse iteration
> Works with any iterable, not just lists

Method 9: Iterating with enumerate() and Conditional Logic

You can combine iteration with conditions easily.

fruits = ['apple', 'banana', 'cherry', 'date']

for i, fruit in enumerate(fruits):
if fruit.startswith(‘b’):
print(f”Found {fruit} at index {i}”)

Output:

Found banana at index 1

Method 10: Using itertools.cycle() or islice() (Advanced)

For advanced looping patterns, Python’s itertools module provides tools for infinite or sliced iterations.

from itertools import cycle, islice

fruits = [‘apple’, ‘banana’, ‘cherry’]

# Repeat list 2 times
for fruit in islice(cycle(fruits), 6):
print(fruit)

Output:

 apple banana cherry apple banana cherry

FAQs — How to Iterate Over a List in Python

How to iterate over a list in Python using a for loop?

The most common way to iterate through a list is with a for loop:

my_list = [10, 20, 30, 40]
for item in my_list:
    print(item)

This prints each element in the list one by one.

How to iterate over a list using index numbers in Python?

Use the range() function with len() to access elements by index:

my_list = ['a', 'b', 'c']
for i in range(len(my_list)):
    print(i, my_list[i])

This gives both index and value from the list.

How to iterate over a list with index and value using enumerate() in Python?

enumerate() lets you loop through both index and value elegantly:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)

This is cleaner and preferred over using range(len()).

How to iterate over a list in reverse order in Python?

Use reversed() or slicing to loop backward:

for item in reversed([1, 2, 3, 4]):
    print(item)

# or
for item in [1, 2, 3, 4][::-1]:
    print(item)
How to iterate over two lists at the same time in Python?

Use the zip() function to combine multiple lists in one loop:

names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 92]

for name, score in zip(names, scores):
    print(name, score)
How to iterate over a list with conditions in Python?

Apply an if statement inside the loop:

numbers = [1, 2, 3, 4, 5]
for n in numbers:
    if n % 2 == 0:
        print(f"{n} is even")
How to iterate over a list and modify its elements in Python?

Use enumerate() with index to modify items in place:

nums = [1, 2, 3]
for i, n in enumerate(nums):
    nums[i] = n * 2
print(nums)

This doubles each number in the list.

How to iterate over a list using while loop in Python?

Use a counter variable to control the loop:

nums = [5, 10, 15]
i = 0
while i < len(nums):
    print(nums[i])
    i += 1
How to iterate through a nested list (list of lists) in Python?

Use nested for loops to go through inner lists:

matrix = [[1, 2], [3, 4], [5, 6]]
for row in matrix:
    for val in row:
        print(val)
How to iterate over a list with list comprehension in Python?

List comprehensions provide a concise way to iterate and transform lists:

nums = [1, 2, 3]
squares = [n**2 for n in nums]
print(squares)


Related Post

Python SetPython Set

Python sets are a fundamental data structure used for storing unordered collections of unique elements. This article dives deep into Python sets, covering their creation, common operations like adding, removing,