Sling Academy
Home/Python/Python: 6 Ways to Iterate Through a List (with Examples)

Python: 6 Ways to Iterate Through a List (with Examples)

Last updated: June 06, 2023

Using a for loop

Using a for loop is the most common approach to iterating through a list in Python. You can access each element individually and perform operations on them as needed.

Example:

# Creating a list
my_list = ["dog", "cat", "rabbit", "parrot", "turtle"]

# Iterating over the list using a for loop
for item in my_list:
    # print each item in uppercase
    print(item.upper())

Output:

DOG
CAT
RABBIT
PARROT
TURTLE

Using the enumerate() function

The Python built-in enumerate() function provides a way to iterate over a list while also tracking the index of each element.

Example:

# Creating a list
fiction_creatures = ["ghost", "goblin", "ghoul", "zombie", "devil", "vampire"]

# Iterating over the list using enumerate()
for index, item in enumerate(fiction_creatures):
      # Print index and value of each element
    print(f"Index: {index}, Value: {item}")

Output:

Index: 0, Value: ghost
Index: 1, Value: goblin
Index: 2, Value: ghoul
Index: 3, Value: zombie
Index: 4, Value: devil
Index: 5, Value: vampire

Using a for loop and the range() function

Besides the enumerate() function mentioned in the previous section, you can use this technique to access both list elements and their indices:

  1. Use the range() function to generate indices corresponding to the list length (returned by the len() function).
  2. Use a for loop to iterate over the range of indices.
  3. Access each element using its index within the loop.

Example:

# Creating a list
my_list = ['Python', 'JavaScript', 'FastAPI', 'Sling Academy']

# Get the length of the list
length = len(my_list)

# Iterating over the list using a for loop and range()
for i in range(length):
    item = my_list[i]  # Accessing each element using its index
    print(item)  # Print each element

Output:

Python
JavaScript
FastAPI
Sling Academy

Using a while loop

A while loop can be used to iterate over a list by incrementing a counter until reaching the list length. It provides flexibility in controlling the loop flow but requires a little additional code.

Example:

# Creating a list
games = ["Elden Ring", "CS:GO", "Dota 2", "League of Legends", "Valorant", "Diablo 4"]

# Iterating over the list using a while loop
counter = 0
while counter < len(games):
    item = games[counter]  # Accessing each element using the counter
    print(item)  # Print each element
    counter += 1  # Increment the counter

Output:

Elden Ring
CS:GO
Dota 2
League of Legends
Valorant
Diablo 4

Using list comprehension

List comprehension is a syntactic construct that allows you to create a new list based on an existing list or another iterable object, using a concise and expressive syntax. Python is one of the few programming languages that support this beautiful syntax (Haskell, C#, Ruby).

Example:

origial_list = ['one', 'two', 'three', 'four', 'five']

# create a new list with uppercase items
new_list = [item.upper() for item in origial_list]
print(new_list)

Output:

['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE']

Using a high-order function

High-order functions like map() and filter() can be used to iterate over a list while applying transformations or filtering based on a condition.

Example of using the map() function:

# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]

# Using map() to square each number
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)

Output:

[1, 4, 9, 16, 25]

Example of using the filter() function:

# Creating a list of numbers
numbers = [1, 2, 3, 4, 5]

# Using filter() to select even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

Output:

[2, 4]

Next Article: Python: Counting the Number of Elements in a List (4 Examples)

Previous Article: Python: How to Access Elements in a List

Series: Python List Tutorials (Basic and Advanced)

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types