Friday, July 1, 2022

Python - Loop through lists

# Loop through a list
thislist = ["apple", "banana", "cherry"]
# This will show each item in the list, one line per item
# apple
# banana
# cherry
for x in thislist:
  print(x)

# 3
print (len(thislist))

# range(0, 3)
print (range(len(thislist)))

print("---")

# This will print each index number of the list: 0, 1, and 2
for i in range(len(thislist)):
  print(i)

# This will print each item in the list
# by specifing each index number in the list:
for i in range(len(thislist)):
    print(thislist[i])

print("---")

# Loop through with a while loop
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
  print(thislist[i])
  i += 1

 
# Looping with "List Comprehension"
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]