How to iterate through a list in Python
In Python, you can use loops to iterate through lists. Commonly used loops include for loops and while loops.
- Use a for loop.
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
Output:
1
2
3
4
5
- Utilizing a while loop:
my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Output:
1
2
3
4
5
It can be seen that using a for loop is more concise and intuitive, while a while loop is relatively more cumbersome. Therefore, when traversing a list, it is recommended to use a for loop.