Iterate over a list in Python¶
The List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size.
In Python , the list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets , lists in Python are ordered and have a definite count. In this article, we will see how to iterate over a list in Python and also Python loop through list of strings.
Python Iterate Over a List¶
Let’s see all the different ways to iterate over a list in Python and the performance comparison between them.
Using for loop
Using for loop and range()
Using a while loop
Using list comprehension
Using enumerate() method
Using the iter function and the next function
Using the map() function
Using zip() Function
Using NumPy module
Iterate over a list using For loop¶
We can iterate over a list in Python by using a simple For loop
1 2 3 4 |
|
1 3 5 7 9
Iterate through a list using for loop and range()¶
In case we want to use the traditional for loop which iterates from number x to number y.
1 2 3 4 5 6 7 |
|
1 3 5 7 9
Iterate through a List in Python using a while loop¶
We can also iterate over a Python list using a while loop .
1 2 3 4 5 6 7 |
|
1 3 5 7 9
Iterate through a list using list comprehension¶
We can use list comprehension (possibly the most concrete way) to iterate over a list in Python.
1 2 3 |
|
1 3 5 7 9
Iterate through a List in Python using enumerate()¶
If we want to convert the list into an iterable list of tuples (or get the index based on a condition check, for example in linear search, you might need to save the index of minimum element), you can use the enumerate() function .
1 2 3 4 5 |
|
0 , 1 1 , 3 2 , 5 3 , 7 4 , 9
Note
Even method 2 can be used to find the index, but method 1 can’t (Unless an extra variable is incremented every iteration) and method 5 gives a concise representation of this indexing
Iterate through a List in Python using the iter function and the next function¶
Here is an additional approach using the iter function and the next function:
1 2 3 4 5 6 7 8 9 10 |
|
1 3 5 7 9
Iterate over a list in Python using the map() function¶
Use the map() function to apply a function to each element of a list.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 3 5 7 9
Python Iterate Over Multiple Lists Using zip() Function¶
In this example, the zip() function is utilized to concurrently iterate over elements from two lists, list1 and list2, pairing corresponding elements together in tuples for subsequent printing.
list1 = [1, 2, 3]
list2 = ['p', 'q', 'r']
# Using zip() to iterate over multiple lists simultaneously
for i1, i2 in zip(list1, list2):
print(f'{i1} -> {i2}')``
1 -> p 2 -> q 3 -> r
Iterate over a list in Python Using NumPy¶
For very large n-dimensional lists (for example an image array), it is sometimes better to use an external library such as numpy . We can use np. enumerate() to mimic the behavior of enumerating. The extra power of NumPy comes from the fact that we can even control the way to visit the elements (Fortran order rather than C order, say :)) but the one caveat is that the np.nditer treats the array as read-only by default, so one must pass extra flags such as op_flags=[‘readwrite’] for it to be able to modify elements.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
0
1
2
3
4
5
6
7
8
Iterate over a list in Python – FAQs¶
How does Python iterate over a list?¶
Python iterates over a list using a for loop. Each element in the list is accessed sequentially. Here’s a basic example:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
In this example, item takes the value of each element in my_list one at a time, and the print function outputs each value.
What are the methods for iterating over a list?¶
There are several methods to iterate over a list in Python:
For Loop: The most common way to iterate over a list.
for item in my_list:
print(item)
While Loop: Uses an index to iterate over the list.
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
List Comprehension: A concise way to create a new list by iterating over an existing one.
new_list = [item * 2 for item in my_list]
Enumerate: Provides both index and value during iteration.
for index, item in enumerate(my_list):
print(index, item)
Map Function: Applies a function to all items in the list.
def square(x):
return x \* x
squared_list = list(map(square, my_list))
What is traversing a list?¶
Traversing a list means accessing and processing each element of the list one by one. This is typically done to perform some operation on each element, such as printing values, modifying them, or applying a function.
How to iterate a list of lists?¶
To iterate over a list of lists, you can use nested for loops. Here’s an example:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for sublist in list_of_lists:
for item in sublist:
print(item)
In this example, sublist takes each list within list_of_lists, and then the inner loop iterates over each item in sublist.
How to iterate through a list function in Python?¶
If you want to use a function to iterate through a list, you can define a function that includes the iteration logic. Here’s an example:
def iterate_and_print(my_list):
for item in my_list:
print(item)
# Example usage
my_list = [1, 2, 3, 4, 5]
iterate_and_print(my_list)
In this function, iterate_and_print, the for loop iterates through my_list and prints each item.
Ready to dive into the future? Mastering Generative AI and ChatGPT is your gateway to the cutting-edge world of AI. Perfect for tech enthusiasts, this course will teach you how to leverage Generative AI and ChatGPT with hands-on, practical lessons. Transform your skills and create innovative AI applications that stand out. Don’t miss out on becoming an AI expert – Enroll now and start shaping the future!