![]() |
VOOZH | about |
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.
We can access all elements using for loop and in keyword to traverse all elements
1 3 5 7 9
This method is similar to the above method. Here we are using a while loop to iterate through a list. We first need to find the length of list using len(), then start at index 0 and access each item by its index then incrementing the index by 1 after each iteration.
1 3 5 7 9
We can also use the enumerate()function to iterate through the list. This method provides both the index (i) and the value (val) of each element during the loop.
0 1 1 3 2 5 3 7 4 9
List comprehension is similar to for loop. It provides the shortest syntax for looping through list.
1 3 5 7 9
Note: This method is not a recommended way to iterate through lists as it creates a new list (extra space).
We can use the range()method with for loop to traverse the list. This method allow us to access elements by their index, which is useful if we need to know the position of an element or modify the list in place.