Iterate over a list in python

There are several ways to iterate over a list in Python. Let`s take a look at different ways to iterate over a list in Python and compare performance between them.

Method # 1: Using a For Loop

# Python3 code to iterate over the list

list = [ 1 , 3 , 5 , 7 , 9 ]

 
# Usage for loop

for i in list :

print (i)

Exit :

 1 3 5 7 9 

Method # 2: For loop and range ()

In case we want to use a traditional for loop that iterates from number x to number y.

# Python3 code to iterate over the list

list = [ 1 , 3 , 5 , 7 , 9 ]

 
# get the length of the list

length = len ( list )

 
# Index iteration
# also like & # 39; for i in the range (len (list)) & # 39;

for i in range (length):

print ( list [i])

Exit:

 1 3 5 7 9 

Index iteration is not recommended if we can iterate over the elements (how is it done in method # 1).

Method # 3: Using a while loop

# Python3 code to iterate over the list

list = [ 1 , 3 , 5 , 7 , 9 ]

 
# Getting list length

length = len ( list )

i =

 
# Iterate using a while loop

while i & lt; length:

print ( list [i])

  i + = 1

Exit:

 1 3 5 7 9 

Method # 4: Using a comprehension list (probably the most specific way).

# Python3 code to iterate over the list

list = [ 1 , 3 , 5 , 7 , 9 ]

 
# Using comprehension list

[ print (i) for i in list ]

Exit:

 1 3 5 7 9 

Method # 5: Using enumerate ()

If we want to convert a list to an iterative list of tuples (or get an index based on conditional checking, for example in linear search you may need to keep the index of the minimum element), you can use the enumerate () function.

# Python3 code to iterate over the list

list = [ 1 , 3 , 5 , 7 , 9 ]

 
# Using enumerate ()

for i, val in enumerate ( list ):

print (i, "," , val)

Exit :

 0, 1 1, 3 2, 5 3 , 7 4, 9 

Note. Even method # 2 can be used to find the index, but method # 1 — does not (unless the additional variable is incremented with each iteration), and method # 5 gives a short view of this indexing.

Method # 6: Using Numpy

For very large n-dimensional lists (like an array of images) it is sometimes better to use an external library such as numpy.

# Python program for
# iterate over the array

import numpy as geek

 
# create an array using
# order method

a = geek.arange ( 9 )

  
# array of form with 3 rows
# and 4 columns

a = a.reshape ( 3 , 3 )

 
# iterate the 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 simulate enumeration behavior. The extra power of numpy comes from the fact that we can even control how elements are visited (Fortran order, not C order, say :)), but the only caveat is that np.nditer is considering an array as read-only. by default, so you need to have additional flags such as op_flags = [& # 39; readwrite & # 39;] to be able to change the elements.