Using for loop and range()
Another way to iterate over a list is by using a for loop in combination with the `range()` function. This method allows you to access the index of each element along with its value.
For example:
Python
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(i, fruits[i])

You can also try this code with Online Python Compiler
Run Code
Output
0 apple
1 banana
2 cherry
In this example, we use the `range()` function to generate a sequence of numbers from 0 to the length of the `fruits` list minus 1. The for loop iterates over these numbers, assigning each number to the variable `i` in each iteration.
Inside the loop, we use `i` as an index to access the corresponding element in the `fruits` list using the indexing syntax `fruits[i]`. This way, we can print both the index and the value of each element.
Note: `range()` is useful when you need to work with the indices of the elements or when you want to modify the list based on the index.
Using a while loop
While loops provide another way to iterate over a list in Python. Unlike for loops, which iterate a fixed number of times, while loops continue to iterate as long as a specified condition is true.
For example :
Python
fruits = ['apple', 'banana', 'cherry']
i = 0
while i < len(fruits):
print(fruits[i])
i += 1

You can also try this code with Online Python Compiler
Run Code
Output
apple
banana
cherry
In this example, we initialize a variable `i` to 0, which will serve as the index for accessing elements in the `fruits` list. The while loop continues to iterate as long as `i` is less than the length of the `fruits` list.
Inside the loop, we use `i` to access the element at the corresponding index using `fruits[i]` and print it. After each iteration, we increment `i` by 1 using the `i += 1` statement to move to the next index.
The while loop continues until `i` becomes equal to the length of the list, at which point the condition `i < len(fruits)` becomes false, and the loop terminates.
Note: While loops offer more flexibility compared to for loops, as you can customize the condition and control the iteration process based on specific requirements. However, for simpler cases, ‘for’ loop would be more useful to use.
Using list comprehension
List comprehension is a concise way to create a new list based on an existing list. It allows you to iterate over a list and perform operations on each element in a single line of code.
For example :
Python
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki']
uppercase_names = [name.upper() for name in names]
print(uppercase_names)

You can also try this code with Online Python Compiler
Run Code
Output
['RAHUL', 'RINKI', 'HARSH', 'SANJANA', 'SINKI']
In this example, we have a list called `names` that contains several names. We use list comprehension to create a new list called `uppercase_names`, which contains the uppercase version of each name in the `names` list.
The list comprehension syntax consists of an expression (`name.upper()`) followed by a for clause (`for name in names`). The expression is applied to each element in the `names` list, and the resulting values are used to create a new list.
List comprehension is a powerful & efficient way to iterate over a list & create new lists based on the original list. It is particularly useful when you want to transform the elements of a list or filter them based on certain conditions.
Using enumerate() method
The `enumerate()` method is a built-in Python function that allows you to iterate over a list & retrieve both the index & the value of each element. It returns an enumerate object that contains tuples of the form (index, value).
For example:
Python
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
for index, name in enumerate(names):
print(f"{index}: {name}")

You can also try this code with Online Python Compiler
Run Code
Output
0: Rahul
1: Rinki
2: Harsh
3: Sanjana
4: Sinki
5: Ravi
6: Mehak
In this example, we use the `enumerate()` method to iterate over the `names` list. The `enumerate()` function takes the list as an argument & returns an enumerate object.
We use tuple unpacking in the for loop to assign the index & value of each element to the variables `index` & `name`, respectively. Inside the loop, we print the index & name using an f-string, which allows us to embed variables directly in the string.
Note: The `enumerate()` method is useful in the situations where you need to keep track of the index while iterating over a list. It eliminates the need for a separate counter variable & makes the code more readable.
Using the iter function and the next function
Python provides the `iter()` function to create an iterator object from a list, and the `next()` function to iterate over the elements of the iterator. This approach gives you more control over the iteration process.
For example:
Python
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
name_iterator = iter(names)
while True:
try:
name = next(name_iterator)
print(name)
except StopIteration:
break

You can also try this code with Online Python Compiler
Run Code
Output
Rahul
Rinki
Harsh
Sanjana
Sinki
Ravi
Mehak
In this example, we use the `iter()` function to create an iterator object called `name_iterator` from the `names` list. The iterator allows us to access the elements of the list one by one.
We start an infinite while loop and use a try-except block to handle the iteration. Inside the loop, we use the `next()` function to retrieve the next element from the `name_iterator`. If there are no more elements, the `next()` function raises a `StopIteration` exception, which we catch in the except block and use to break out of the loop.
Note: This method is useful when you need more control over the iteration process or when you want to implement custom iteration behavior. However, for most common cases, you should always use “for” loop.
Using the map() function
The `map()` function is a built-in Python function that allows you to apply a function to each element of a list & create a new list with the results. It provides a concise way to iterate over a list & perform transformations.
For example:
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
def capitalize_name(name):
return name.capitalize()
capitalized_names = list(map(capitalize_name, names))
print(capitalized_names)
Output
['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
In this example, we define a function called `capitalize_name()` that takes a name as input & returns the capitalized version of the name using the `capitalize()` method.
We then use the `map()` function to apply the `capitalize_name()` function to each element of the `names` list. The `map()` function returns a map object, which we convert to a list using the `list()` function.
The resulting `capitalized_names` list contains the capitalized versions of the names from the original `names` list.
Note: The `map()` function is useful when you want to apply a specific function to each element of a list & create a new list with the transformed values. It provides a easy, short & functional way to iterate over a list & perform operations on its elements.
Using zip() Function
The `zip()` function in Python allows you to iterate over multiple lists simultaneously. It takes two or more lists as arguments and returns an iterator of tuples, where each tuple contains the corresponding elements from the input lists.
For example:
Python
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
ages = [25, 30, 27, 24, 28, 32, 29]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")

You can also try this code with Online Python Compiler
Run Code
Output
Rahul is 25 years old.
Rinki is 30 years old.
Harsh is 27 years old.
Sanjana is 24 years old.
Sinki is 28 years old.
Ravi is 32 years old.
Mehak is 29 years old.
In this example, we have two lists: `names` containing names and `ages` containing corresponding ages. We use the `zip()` function to iterate over both lists simultaneously.
The `zip()` function returns an iterator of tuples, where each tuple contains the elements from the corresponding positions of the input lists. We use tuple unpacking in the for loop to assign the name and age to the variables `name` and `age`, respectively.
Inside the loop, we print a formatted string that combines the name and age using an f-string.
The `zip()` function is useful in those cases where you have multiple lists that you want to iterate over in parallel. It allows you to access the elements from different lists at the same index in each iteration.
Note: Just remember, that if the lists have different lengths, the `zip()` function will stop iterating when the shortest list is exhausted.
Using NumPy module
NumPy is a powerful library for numerical computing in Python. It provides efficient ways to work with arrays and perform mathematical operations. NumPy also offers methods to iterate over arrays, which can be used to iterate over lists.
For example :
Python
import numpy as np
names = ['Rahul', 'Rinki', 'Harsh', 'Sanjana', 'Sinki', 'Ravi', 'Mehak']
ages = [25, 30, 27, 24, 28, 32, 29]
# Convert lists to NumPy arrays
name_array = np.array(names)
age_array = np.array(ages)
for name, age in np.nditer([name_array, age_array]):
print(f"{name} is {age} years old.")

You can also try this code with Online Python Compiler
Run Code
Output
Rahul is 25 years old.
Rinki is 30 years old.
Harsh is 27 years old.
Sanjana is 24 years old.
Sinki is 28 years old.
Ravi is 32 years old.
Mehak is 29 years old.
In this example, we first import the NumPy module using `import numpy as np`. We have two lists: `names` containing names and `ages` containing corresponding ages.
We convert the lists to NumPy arrays using the `np.array()` function, which creates `name_array` and `age_array` respectively.
To iterate over the arrays, we use the `np.nditer()` function, which returns an iterator that allows us to iterate over multiple arrays simultaneously. We pass a list of arrays (`[name_array, age_array]`) to `np.nditer()`.
Inside the for loop, we use tuple unpacking to assign the name and age to the variables `name` and `age`, respectively. We then print a formatted string that combines the name and age using an f-string.
Frequently Asked Questions
Can we modify the elements of a list while iterating over it using a for loop?
It's generally not recommended to modify a list while iterating over it using a for loop, as it can lead to unexpected behavior. Instead, you can create a new list with the modified elements or use a list comprehension.
What happens if we try to iterate over an empty list?
If you try to iterate over an empty list, the loop will simply skip the iteration part and move on to the next line of code. No error will be raised, and the loop will terminate immediately.
Can we iterate over multiple lists of different lengths using the zip() function?
Yes, you can iterate over multiple lists of different lengths using the zip() function. However, the iteration will stop when the shortest list is exhausted. If you want to continue iterating until the longest list is exhausted, you can use itertools.zip_longest() instead.
Conclusion
In this article, we learned about different ways to iterate over a list in Python. We explained this using for loops, while loops, list comprehension, the enumerate() method, the iter() and next() functions, the map() function, the zip() function, and the NumPy module.