Iterate over a list in Python
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.
Ways to Iterate over a list in Python
There are multiple ways to iterate over a list in Python. Let’s see all the different ways to iterate over a list in Python, and performance comparison between them.
Method 1: Using For loop
We can iterate over a list in Python by using a simple For loop.
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # Using for loop for i in list : print (i) |
Output:
1 3 5 7 9
Time complexity: O(n) – where n is the number of elements in the list.
Auxiliary space: O(1) – as we are not using any additional space.
Method 2: For loop and range()
In case we want to use the traditional for loop which iterates from number x to number y.
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # getting length of list length = len ( list ) # Iterating the index # same as 'for i in range(len(list))' for i in range (length): print ( list [i]) |
Output:
1 3 5 7 9
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), which is constant space
Method 3: Using a while loop
We can also iterate over a Python list using a while loop.
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # Getting length of list length = len ( list ) i = 0 # Iterating using while loop while i < length: print ( list [i]) i + = 1 |
Output:
1 3 5 7 9
Time complexity: O(n) where n is the length of the list.
Auxiliary space: O(1) as only a constant amount of extra space is used for variables i and length.
Method 4: Using list comprehension
We can use list comprehension(possibly the most concrete way) to iterate over a list in Python.
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # Using list comprehension [ print (i) for i in list ] |
Output:
1 3 5 7 9
Method 5: 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.
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # Using enumerate() for i, val in enumerate ( list ): print (i, "," ,val) |
Output:
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.
Method 6: 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.
Python3
# Python program for # iterating over array import numpy as geek # creating an array using # arrange method a = geek.arange( 9 ) # shape array with 3 rows # and 4 columns a = a.reshape( 3 , 3 ) # iterating an array for x in geek.nditer(a): print (x) |
Output:
0 1 2 3 4 5 6 7 8
We can use np.ndenumerate() 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.
Method 7: Using the iter function and the next function
Here is an additional approach using the iter function and the next function:
Python3
# Python3 code to iterate over a list list = [ 1 , 3 , 5 , 7 , 9 ] # Create an iterator object using the iter function iterator = iter ( list ) # Use the next function to retrieve the elements of the iterator try : while True : element = next (iterator) print (element) except StopIteration: pass |
1 3 5 7 9
Time complexity: O(n), where n is the length of the list, because it iterates through the elements of the list once and performs a constant number of operations on each element.
Auxiliary space: O(1), because it does not create any additional data structures to store intermediate results or the final result.
Method 8: Using the map() function
Use the map() function to apply a function to each element of a list.
Python3
# Define a function to print each element def print_element(element): print (element) # Create a list my_list = [ 1 , 3 , 5 , 7 , 9 ] # Use map() to apply the print_element() function to each element of the list result = map (print_element, my_list) # Since map() returns an iterator, we need to consume # the iterator in order to see the output for _ in result: pass |
1 3 5 7 9
Time complexity: O(n), where n is the length of the list.
Auxiliary space: O(1)
Please Login to comment...