list = [1, 3, 5, 7, 9]
# with index
for index, item in enumerate(list):
print (item, " at index ", index)
# without index
for item in list:
print(item)
# Python code to iterate over a list
list = [1, 2, 3, 4, 5, 6]
# Method 1: Using "var_name in list" syntax
# Pro: Consise, easily readable
# Con: Can't access index of item
for item in list:
print(item)
# Method 2: Using list indices
# Pro: Can access index of item in list
# Con: Less consise, more complicated to read
for index in range(len(list)-1):
print(list[index])
# Method 3: Using enumerate()
# Pro: Can easily access index of item in list
# Con: May be too verbose for some coders
for index, value in enumerate(list):
print(value)
# a 'while' loop runs until the condition is broken
a = "apple"
while a == "apple":
a = "banana" # breaks loop as 'a' no longer equals 'apple'
# a 'for' loop runs for the given number of iterations...
for i in range(10):
print(i) # will print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# ... or through a sequence
array = [3, 6, 8, 2, 1]
for number in array:
print(number) # will print 3, 6, 8, 2, 1