Skip to content

How to Iterate Through a List in Python

February 20, 2021

In this quick tutorial, we will explore different ways to iterate through a list in Python. We will cover the following methods:

Follow are the way using which you iterate over the list in Python:

  1. Using a for loop
  2. Using the enumerate() function
  3. Using a while loop
  4. List comprehension
  5. Using the itertools module

 

Let’s get started!

 

1 – Using a for loop:

The simplest way to iterate through a list is by using a for loop. Here’s an example:

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

for fruit in fruits:
    print(fruit)

 

2 – Using the enumerate() function:

If you want to keep track of the index while iterating, you can use the enumerate() function:

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

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

 

3 – Using a while loop:

While less common, you can also use a while loop to iterate through a list:

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

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

 

4 – List comprehension:

List comprehensions are a concise way to iterate through a list and create a new list based on a condition or applying a function:

fruits = ['apple', 'banana', 'cherry']
fruits_upper = [fruit.upper() for fruit in fruits]

print(fruits_upper)

 

5 – Using the itertools module:

The itertools module provides several functions that can be used to iterate through a list. For example, the itertools.cycle() function can be used to iterate through a list indefinitely:

import itertools

fruits = ['apple', 'banana', 'cherry']
cycle_fruits = itertools.cycle(fruits)

for i, fruit in zip(range(6), cycle_fruits):
    print(f"{i}: {fruit}")

 

In summary, there are multiple ways to iterate through a list in Python. The most common methods are using a for loop and the enumerate() function. However, other methods like while loops, list comprehensions, and itertools module functions can also be used depending on the specific requirements of your code.