Background
In this post, we will see the different ways to iterate over a list in Python.
Different ways to iterate over a list in Python
Using for loop
A simple way to iterate over a list is to use a for loop.
1 2 3 | names = [ "A" , "B" , "C" ] for name in names: print(name) |
This prints
A
B
C
Using for loop with range
You can also use a for loop with range if you want to access the list with it's index
1 2 3 | names = [ "A" , "B" , "C" ] for name in names: print(name) |
This also prints
A
B
C
Using enumerate
If you want index and value both then you can use enumerate as follows
1 2 3 | names = [ "A" , "B" , "C" ] for idx, name in enumerate(names): print(f "{name} at index {idx}" ) |
This prints
A at index 0
B at index 1
C at index 2
Using while loop
You can also use a while loop for iterating over a list as follows
1 2 3 4 5 | names = [ "A" , "B" , "C" ] i= 0 while i<len(names): print(names[i]) i = i + 1 |
This prints:
A
B
C
List Comprehension
List comprehension is a more concise way to iterate over a list.
1 2 | names = [ "A" , "B" , "C" ] [print(name) for name in names] |
This prints:
A
B
C
If you print above list it will print [None, None, None] as you are not creating any new element for storing in new list on iterating the original list
NOTE: This creates a new list and is not a recommended way to iterate over a list. You can use this if you have a usecase to create a new list from existing one with filtering or modifying the original list.