Change language

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.

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically