Different ways to Loop through a Python List
A list in Python is a data structure that holds data as a sequence. Looping through a list enables you to access each element one by one, making it possible to perform operations such as data manipulation, analysis, or processing.
Python is so versatile that we can loop through the List using multiple ways. Let us go through each one by one.
Using for Loop
We can iterate over all the items in the list using a for
loop. This is the most common way to iterate through a list.
birdslist = ["Parrot", "Crow", "Eagle"]
for bird in birdslist:
print(bird)
for Loop using range() function – Loop through index numbers
We can use the index positions of the list items to loop through the list. The len() functions is used to find out the length of the list, and then we will use the range() function to iterate through the index positions up to the length of the list.
This method gives us more control over the simple for loop, allowing us to access both the index and the corresponding element.
birdslist = ["Parrot", "Crow", "Eagle"]
for i in range(len(birdslist)):
print(birdslist[i])
Using while loop
While loop can also be used to iterate over the list. This method is not as popular as the for loop, but yes, can be useful in some situations.
Here, we will initialize a variable with index position 0. While loop will go up to the length of the list and on every iteration, we will increase the value of the variable containing index position by 1.
birdslist = ["Parrot", "Crow", "Eagle"]
i = 0
while i < len(birdslist):
print(birdslist[i])
i = i + 1
Using List Comprehension
List comprehension provides us powerful functionality to iterate through a list in a single line of code. It is one of the most robust ways to create the list and iterate through the list.
Here, in the below example, we will iterate over the numbers list, square each number using list comprehension and print squares list.
In the second example, we are using list comprehension to print each number. Here, the temp variable is used to hold the list returned by list comprehension.
Square of numbers.
numbers = [1, 2, 3, 4, 5]
squares = [i**2 for i in numbers]
print(squares)
Printing each number.
numbers = [1, 2, 3, 4, 5]
temp = [print(i) for i in numbers]
Using enumerate()
The enumerate function provides us the more Pythonic way to loop through both the index and the element of the list.
The enumerate() function is a built-in function that allows you to loop over an iterable while keeping track of both the index and the corresponding element in each iteration. This is more useful when you need to know the position of an element within the list.
It returns pairs of (index, element), and we use a loop to unpacks these pairs into the variables index and element.
list = ['a', 'b', 'c', 'd', 'e']
for i, val in enumerate(list):
print (i, "-",val)
Using the map() function
The map() function is a built-in function that applies a provided function to all the items in an iterable, e.g. a list in this case, and returns an iterator that produces the results.
In the below example, we will map the print_number function to each item of the numbers list, and it will print the numbers. The result variable will not hold anything other than none’s because we are not returning anything from the list.
# Define a function to print each element
def print_number(number):
print(number)
numbers = [1, 2, 3, 4, 5]
# map() will apply the print_number() function to each element of the list numbers
result = list(map(print_number, numbers))
Using zip() Function
The zip() function can also be used to iterate over the elements of the two or more lists. It will return us the tuples, each tuple having one element from each list.
numbers = [24, 25, 26]
characters = ['x', 'y', 'z']
# zip() to iterate over both the lists
for i, j in zip(numbers, characters):
print(i, "-", j)
Using the iter() and next() functions
The iter() function is used to obtain an iterator from an iterable object. The next() function is used to retrieve the next element from an iterator.
In the below example, we are using the iter() function to create the iterator of the numbers, and next is used to fetch the next element.
numbers = [1, 2, 3, 4, 5]
# Creating an iterator object
iterator = iter(numbers)
# printing elements of list
# The next function is retrieving elements
try:
while True:
item = next(iterator)
print(item)
except StopIteration:
pass