How to iterate over a list in Python

Key takeaways:

  • Python offers multiple ways to iterate over lists beyond the basic for loop, including list comprehension, iter() and next(), zip(), and map(), each enhancing efficiency and readability.

  • Functions like enumerate() (for index-value pairs), zip() (for parallel iteration), and itertools (for optimized iteration) provide powerful alternatives for various iteration scenarios.

  • The for-else construct enables executing specific actions if a loop completes normally while handling StopIteration in iterators prevents errors during iteration.

Methods to iterate over a list

Iterating over their elements is a fundamental task when working with lists in Python. While the basic for loop suffices for most scenarios, there are advanced techniques that can enhance the code’s readability and efficiency. In this Answer, we’ll delve into the following methods of list iteration:

  • Using a while loop

  • Using list comprehension

  • Using iter() and the next() function

  • Using the for loop with range()

  • Using the for-else construct

  • Using the zip() function

  • Using the itertools module

  • Using the enumerate() function

  • Using the map() function

1. Using a while loop

A while loop can iterate over a list by manually maintaining an index variable.

my_list = [1, 2, 3, 4, 5]
i = 0 # Initialize index
while i < len(my_list): # Condition to avoid out-of-bounds error
print(my_list[i]) # Output: 1 2 3 4 5
i += 1 # Increment index

The loop runs as long as i is within the list’s range. The index i is manually updated.

2. Using list comprehension

List comprehension is a concise way to create a new list by applying an operation to each element of an existing list. It is preferred for its readability and efficiency.

my_list = [1, 2, 3, 4, 5]
squared_list = [x**2 for x in my_list] # Squaring each element
print(squared_list) # Output: [1, 4, 9, 16, 25]

The expression [x**2 for x in my_list] iterates through my_list, squaring each element.

3. Using iter() and next()

The iter() function converts a list into an iterator, and next() retrieves elements individually. When there are no more elements, next() raises a StopIteration exception, which can be handled with a try-except block.

my_list = [1, 2, 3, 4, 5]
iterator = iter(my_list) # Convert list into an iterator
while True:
try:
item = next(iterator) # Get next element
print(item) # Output: 1 2 3 4 5
except StopIteration:
break # Exit loop when iteration is complete

iter(my_list) creates an iterator object. next(iterator) retrieves the next item. When all elements are executed, StopIteration is raised, and the loop exits.

4. Using the for loop with range()

A for loop with range() is commonly used when you need index-based access to list elements.

my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)): # Loop over indices
print(my_list[i]) # Output: 1 2 3 4 5

range(len(my_list)) generates indexes from 0 to len(my_list) - 1. my_list[i] accesses each element using the index.

5. Using the zip() function

The zip() function is a powerful tool for iterating over multiple lists simultaneously. Combining elements from different lists in pairs allows us to traverse them in parallel and perform operations on corresponding items. This is particularly useful when dealing with related data sets. For instance, pairing up names and corresponding ages becomes a breeze:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 28]
def iterate_using_zip_function(names, ages):
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
iterate_using_zip_function(names, ages)

In the code above, zip() pairs the names and ages lists, allowing us to iterate over both lists simultaneously and print the names and ages together.

6. Using itertools module

The itertools module provides functions for efficient iteration. Here are two common ways to iterate using it:

1. Using itertools.cycle()

import itertools
my_list = [1, 2, 3]
cycler = itertools.cycle(my_list)
for _ in range(7): # Avoid infinite loop
print(next(cycler), end=" ") # Output: 1 2 3 1 2 3 1

itertools.cycle(my_list) creates an infinite loop over my_list. Calling next(cycler) retrieves the next item cyclically.

2. Using itertools.islice() (Iterate over a subset)

import itertools
my_list = [1, 2, 3, 4, 5]
sliced_iter = itertools.islice(my_list, 2, 4) # Get items from index 2 to 4
for item in sliced_iter:
print(item) # Output: 3 4

islice(my_list, 2, 4) selects a subset of my_list (from index 2 to 4). This avoids creating a new list and saving memory.

7. Using the for-else construct

Python’s for loops can be extended with an else block that executes if the loop completes normally (i.e., without encountering a break statement). This is useful for scenarios where you want to perform actions only if the loop runs to completion:

ages = [25, 30, 28]
def iterate_using_zip_function(ages):
for item in ages:
if item == 30:
print("Found Thirty")
break
else:
print("Not found")
iterate_using_zip_function(ages)

In the code above, the for loop iterates through the list ages and checks if any item equals 30. If found, the break statement is executed, and the else block is skipped. If not found, the loop completes normally, and the else block prints Not found.

8. Using the enumerate() function

When you need both the index and the value of an element during iteration, the enumerate() function is the go-to solution for us. It returns tuples containing both the index and the corresponding value, simplifying the process of tracking positions:

names = ["Alice", "Bob", "Charlie"]
def iterate_using_enumerate_function(names):
for index, name in enumerate(names):
print(f"At index {index}, we have {name}.")
iterate_using_enumerate_function(names)

As we iterate through the list names, the enumerate function pairs up each name with its respective index, i.e., Alice with 0, Bob with 1, and Charlie with 2.

9. Using the map() function

The map() function concisely applies a specific operation to each element in a list, returning an iterator of the results. This is particularly handy when transforming elements based on a predefined function:

ages = [25, 30, 28]
def iterate_using_map_function(ages):
squared_numbers = map(lambda x: x ** 2, ages)
print(list(squared_numbers))
iterate_using_map_function(ages)

In the code above, the map() function applies the lambda function (which squares a number) to each number in the ages list. The result is an iterator with squared values, which are then converted to a list and printed.

Learn the basics with our engaging “Learn Python” course!

Start your coding journey with Learn Python, the perfect course for beginners! Whether exploring coding as a hobby or building a foundation for a tech career, this course is your gateway to mastering Python—the most beginner-friendly and in-demand programming language. With simple explanations, interactive exercises, and real-world examples, you’ll confidently write your first programs and understand Python essentials. Our step-by-step approach ensures you grasp core concepts while having fun. Join now and start your Python journey today—no prior experience is required!

Conclusion

Mastering advanced list iteration techniques in Python enhances code efficiency and readability. From concise methods like list comprehension and map() to powerful utilities like zip(), enumerate(), and itertools, Python offers a range of tools to handle different iteration scenarios. Understanding these techniques allows developers to write cleaner, more performant code while improving their ability to manipulate and process data effectively.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to pull a value from a list in Python

  • Using indexing: Python uses zero-based indexing, which means that the first element in a list has an index of 0. You can access an element by its index using square brackets [].
  • Negative indexing: You can also use negative indexes to access elements from the end of the list. -1 refers to the last element. -2 refers to the second-to-last 1 element, and so on.

What is slicing in Python?

Slicing is a powerful technique that allows you to extract a portion of a list.

Syntax: list[start:stop:step]

  • start (inclusive): The index of the first element to include (default is 0).
  • stop (exclusive): The index of the element after the last element to include.
  • step (optional): The step size (default is 1).

The step size determines how many elements to skip.

Example:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Extract every 2nd element
print(numbers[::2])  # Output: [0, 2, 4, 6, 8]

# Extract every 3rd element
print(numbers[::3])  # Output: [0, 3, 6, 9]

# Reverse the list using a negative step
print(numbers[::-1])  # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This demonstrates how step size controls the slicing behavior.


What is [:] in Python?

[:] is a slicing operation that creates a shallow copy of a list or sequence. It selects all elements without modifying the original list. It can also be used to extract a subset of a sequence.

Example:
original_list = [1, 2, 3, 4, 5]
copy_list = original_list[:]

print(copy_list)  # Output: [1, 2, 3, 4, 5]
print(copy_list is original_list)  # Output: False (it's a new list)
Use cases:
  • Creating a copy of a list (new_list = old_list[:])
  • Resetting a list (my_list[:] = [] clears all elements)
  • Works on strings, tuples, and other sequences

How do you iterate a list in Python?

You can iterate over a list using a for loop:

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

Or using enumerate() if you need the index:

for index, item in enumerate(my_list):
    print(index, item)

How to repeat items in a list in Python

You can use the * operator to repeat a list:

my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list)  # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

To repeat each element individually:

from itertools import chain

my_list = [1, 2, 3]
repeated_items = list(chain.from_iterable([[x]*3 for x in my_list]))
print(repeated_items)  # Output: [1, 1, 1, 2, 2, 2, 3, 3, 3]

How to call a list in a for loop in Python

If you want to use a list inside a for loop, just reference its name:

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

Or using a function:

def process_list(lst):
    for item in lst:
        print(item)

process_list([5, 15, 25])

How to iterate through a list of words in Python

You can iterate through a list of words in Python using a for loop:

words = ["apple", "banana", "cherry"]

for word in words:
    print(word)

Using enumerate() (if you need the index)

for index, word in enumerate(words):
    print(index, word)

Using a while loop

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

Using list comprehension (if you need to process words)

[print(word) for word in words]

These methods work efficiently for iterating through a list of words in Python.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved