Iterate Through a List in Python

Python offers multiple ways to iterate through a list, depending on whether you need just the items or both the items and their indices.

Using a for Loop

The for loop is the most common and straightforward way to iterate over a list in Python. It allows you to directly access each element in the list.

For example:

fruits = ["apple", "banana", "mango", "orange"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango
orange

Using a for Loop With range() (For Index-Based Access)

This approach uses the range() function to generate indices, which are then used to access elements based on their positions.

For example:

fruits = ["apple", "banana", "mango", "orange"]
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

Output:

0: apple
1: banana
2: mango
3: orange

Using a for Loop and enumerate() (For Simultaneous Index and Value Access)

If you need to access both the index and the value, you can use this approach.

For example:

fruits = ["apple", "banana", "mango", "orange"]
for index, value in enumerate(fruits):
    print(f"{index}: {value}")

Output:

0: apple
1: banana
2: mango
3: orange

Using a while Loop

You can use a while loop to iterate through the list, but you need to manage the index manually.

For example:

fruits = ["apple", "banana", "mango", "orange"]
# Initialize Index
i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1

Output:

apple
banana
mango
orange

Using List Comprehension (For Creating New Lists Based on Iteration)

List comprehensions provide a concise way to create new lists by applying an expression to each item in an existing iterable (such as a list, a tuple, or a range).

For example:

numbers = [1, 2, 3, 4]

squared_numbers = [num ** 2 for num in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16]