Given a list, the task is to iterate over all its elements. For Example:
Input: a = [10, 20, 30]
Output:
10
20
30
Now, let's explore different methods to iterate over a list in Python.
Using for Loop
for loop is the common way to iterate over a list. It directly accesses each element without requiring index management, making the code simple and easy to read.
a = [1, 3, 5, 7, 9]
for x in a:
print(x)
Output
1 3 5 7 9
Explanation: loop visits each element of the list one at a time, assigning it to x and printing its value.
Using enumerate()
enumerate() function is useful when you need both the index and the corresponding element while iterating through a list.
a = [1, 3, 5, 7, 9]
for i, x in enumerate(a):
print(i, x)
Output
0 1 1 3 2 5 3 7 4 9
Explanation: enumerate() returns both the index (i) and the element (x) during each iteration, allowing you to access both values together.
Using while Loop
A while loop iterates through a list by accessing elements using their indices. This approach is useful when you need more control over the iteration process.
a = [1, 3, 5, 7, 9]
i = 0
while i < len(a):
print(a[i])
i += 1
Output
1 3 5 7 9
Explanation: loop starts from index 0, prints the element at the current index, increments the index, and continues until all elements have been processed.
Using range() with for Loop
range() function can be combined with a for loop to iterate through the indices of a list. This method is helpful when the element's position is also required.
a = [1, 3, 5, 7, 9]
for i in range(len(a)):
print(a[i])
Output
1 3 5 7 9
Explanation: range(len(a)) generates all valid indices of the list. Each index is then used to access and print the corresponding element.