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
|
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.
|
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
|
Exit:
1 3 5 7 9
Method # 4: Using a comprehension list (probably the most specific way).
|
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.
|
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.
|
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.