Iterating over lists in Python
The range(len()) method utilizes the range() and len() functions in python. The len() function gets the number of elements in the list and range() function generates a range of values that are same as the indices of the list elements. We can then iterate over the indices using a for loop.
# range(len())
# create lists
a = [1,2,3,4,5]
b = [4,2,7,1,9]
c = [9,8,4,7,6]
#create empty list to store results
d = []
#loop
for i in range(len(a)):
d.append(a[i] * b[i] * c[i])
print(f'{d=}')
d=[36, 32, 84, 28, 270]
a = [1,2,3]
for i in zip(a):
print(i)
(1,) (2,) (3,)
The zip function can take multiple lists at a time. Even if the number of elements in two lists is unequal, the zip function creates tuple until the samllest list is iterated over.
a = [1,2,3]
b = ["a","b","c","d"]
c = [5,6,7,8,9]
for i,j,k in zip(a,b,c):
print(i,j,k)
1 a 5 2 b 6 3 c 7
When we have several lists to iterate over simultaneously, the zip function may very tedious to use. Python has another function, enumerate(), which iterates over a list and also keeps a count.
a = ["a","b","c","d"]
for i, el in enumerate(a):
print(i, el)
0 a 1 b 2 c 3 d
The enumerate function has two arguments. First is the iterable variable and second is the "start" from where the counting needs to start. The default value of start is 0. We can use other value for start as follows.
a = ["a","b","c","d"]
for i, el in enumerate(a, start=5):
print(i, el)
5 a 6 b 7 c 8 d