Iterate Through a List in Python
Python offers several ways to iterate through a list in Python. Here are the most common methods:
(1) Using for loop
The for
loop is the most common and straightforward way to iterate through a list in Python. It directly accesses each element in the list.
For example:
my_list = [5, 10, 15, 20]
for item in my_list:
print(item)
Output:
5
10
15
20
Using for loop with range()
If you need to get the index of each item while iterating, you can use the range()
function with the list’s length.
For example:
my_list = ["apple", "banana", "mango"]
for i in range(len(my_list)):
print(f"{i}: {my_list[i]}")
Output:
0: apple
1: banana
2: mango
The len()
function returns the number of items in an object (in our case list).
The range()
function generates a sequences of numbers within a specified range.
Using for loop with enumerate()
If you need to get both the value and index of each item during iteration, you can you the enumerate()
function.
For example:
my_list = ["apple", "banana", "mango"]
for index, fruit in enumerate(my_list):
print(index, fruit)
Output:
0 apple
1 banana
2 mango
(2) Using while loop
You can use while
loop to iterate through a list if you need manual control over the index, giving you more flexibility to skip elements or change the loop’s behavior.
Here’s a simple example of a while loop
my_list = ["apple", "banana", "mango"]
# Initialize index
index = 0
while index < len(my_list):
print(my_list[index])
index += 1
Output:
apple
banana
mango
You need to manage the index manually.
Let’s take a look at another example that skips even numbers.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Initialize index
index = 0
while index < len(my_list):
# Skip even numbers
if my_list[index] % 2 == 0:
index += 1
continue
print(my_list[index]) # Print odd number
index += 1
Output:
1
3
5
7
9
(3) Using list comprehension
List comprehensions are commonly used to create new lists from existing iterables (like lists, tuples, or ranges), but they can also be used for iterating over lists.
For example:
my_list = ["apple", "banana", "mango"]
[print(fruit) for fruit in my_list]
Output:
apple
banana
mango
List comprehension are particularly useful when you need to create a new list by applying an expression to each item in an existing iterable (such as lists, tuples, or sets), optionally including a condition to fiter the items.
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create a list of even numbers
even_numbers = [num for num in my_list if num % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8]
Choosing the right method
Use for
loop if you only need the values.
Use for
loop with range()
function if you need the index.
Use for
loop with enumerte()
function if you need both the index and value.
Use while
loop if you need manual control the index or iteration step.
Use list comprehension if you need to create a new list with optional conditions or transformations.