Python - Loop Lists
Loop Through a List
You can loop through the list items by using afor
loop:
Example
Print all items in the list, one by one:
for x in thislist:
print(x)
Learn more aboutfor
loops in ourPython For Loops Chapter.
Loop Through the Index Numbers
You can also loop through the list items by referring to their index number.
Use therange()
andlen()
functions to create a suitable iterable.
Example
Print all items by referring to their index number:
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is[0, 1, 2]
.
Using a While Loop
You can loop through the list items by using awhile
loop.
Use thelen()
function to determine the length of the list,then start at 0 and loop your way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using awhile
loop to go through all the index numbers
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
Learn more aboutwhile
loops in ourPython While Loops Chapter.
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists:
Example
A short handfor
loop that will print all items in a list:
[print(x) for x in thislist]
Learn more about list comprehension in the next chapter:List Comprehension.