Loading lessons...
Loop Through Lists
Loop Through Lists
There are several ways to visit every item in a list.
For loop with in
The simplest way:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Loop by index
for i in range(len(thislist)):
print(thislist[i])
While loop
i = 0
while i < len(thislist):
print(thislist[i])
i += 1
List comprehension (compact)
[print(x) for x in thislist]
This is the fastest and shortest way, and it's very common in real Python code.
Loop with index using enumerate
for i, x in enumerate(thislist):
print(i, x)
TL;DR
for x in lstis the cleanest loop.range(len(lst))loops by index.- List comprehension can print in one line.
enumerategives index and item together.