• List is like arrays in other languages, with the extra advantage of being dynamic in size. In Python, the list may be a sort 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.
  • There are multiple ways to iterate over a list in Python. Let’s see all the various ways to iterate over a list in Python, and performance comparison between them.

Method #1: Using For loop

# 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

Method #2: For loop and range ()

In case we would like to use the traditional for loop which iterates from number x to number y.

# 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

Iterating using the index isn’t recommended if we will iterate over the elements (as done in Method #1).

Method #3: Using while loop

# 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

Method #4: Using list comprehension (Possibly the most concrete way).

# 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 would like to convert the list into an iterable list of tuples (or get the index supported a condition check, for example in linear search you would possibly need to save the index of minimum element), you’ll use the enumerate() function.

# 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 is used to find the index, but method #1 can’t (Unless an additional variable is incremented every iteration) and method #5 gives a concise representation of this indexing.

Categorized in: