Looping through a list
Here are two ways to iterate over items in a list, similar to iterating over characters in a string.
Loop through all list items
This is the easiest way to iterate over all the items in a list, since you won't need the index of each item:
lst = [3, 5, 8, 9]
for num in lst:
print(num)
Console results:
3
5
8
9
Loop through list indices
If you need to use the list index in the loop body, then you can iterate over the indices instead by using i
as the index in the list:
lst = [3, 5, 8, 9]
for i in range(len(lst)):
print(i, lst[i])
Console results:
0 3
1 5
2 8
3 9