How to iterate over a list in Python?
Published on July 20, 2023
List Iteration Methods in Python
Using the zip()
Function:
zip()
combines multiple iterable objects element-wise.- It returns an iterator of tuples containing elements from the input iterables at the same index.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
# Using zip() for iteration
for num, letter in zip(list1, list2):
print(num, letter)
Using the itertools
Module:
- The itertools module provides functions for creating and manipulating iterators efficiently.
itertools.cycle()
creates an infinite iterator cycling through elements of an iterable.
from itertools import cycle
colors = ['red', 'green', 'blue']
color_cycle = cycle(colors)
# Iterating infinitely through the cycle
for i in range(10):
print(next(color_cycle))
Using the enumerate()
Function:
enumerate()
is used to iterate over elements in a list while keeping track of their index or position.- It returns tuples containing both the index and the element.
fruits = ['apple', 'banana', 'cherry']
# Using enumerate() for iteration with index
for index, fruit in enumerate(fruits):
print(index, fruit)
Using the map()
Function:
map()
applies a specified function to each item in an iterable and returns an iterable containing the results.- It can be useful for performing operations on all elements of a list and collecting the results.
def square(x):
return x * x
numbers = [1, 2, 3, 4]
# Using map() to apply the square function
squared_numbers = map(square, numbers)
# Converting the result to a list
squared_numbers = list(squared_numbers)
print(squared_numbers)