1fruits = ["apple", "banana", "strawberry"]
2
3for fruit in fruits:
4 print(fruit)
5 #This "for fruit in fruits" gets every item in order from that list and does something with it
6 #for example I print the fruit
7 #note: This loop will only end when there aren't any items left in the list
8 #example: After strawberry there isn't anything else soo the loop ends
9#output: apple
10 #banana
11 #stawberry
1list = [1, 3, 5, 7, 9]
2
3# with index
4for index, item in enumerate(list):
5 print (item, " at index ", index)
6
7# without index
8for item in list:
9 print(item)
1foo = ['foo', 'bar']
2for i in foo:
3 print(i) #outputs 'foo' then 'bar'
4for i in range(len(foo)):
5 print(foo[i]) #outputs 'foo' then 'bar'
6i = 0
7while i < len(foo):
8 print(foo[i]) #outputs 'foo' then 'bar'
1# Python code to iterate over a list
2list = [1, 2, 3, 4, 5, 6]
3
4# Method 1: Using "var_name in list" syntax
5# Pro: Consise, easily readable
6# Con: Can't access index of item
7for item in list:
8 print(item)
9
10# Method 2: Using list indices
11# Pro: Can access index of item in list
12# Con: Less consise, more complicated to read
13for index in range(len(list)-1):
14 print(list[index])
15
16# Method 3: Using enumerate()
17# Pro: Can easily access index of item in list
18# Con: May be too verbose for some coders
19for index, value in enumerate(list):
20 print(value)
21
1lst = [10, 50, 75, 83, 98, 84, 32]
2
3for x in range(len(lst)):
4 print(lst[x])
5