tayrix tayrix - 28 days ago 6
Python Question

Python List Multiple Iterations

If someone would like to iterate through multiple lists with multiple iteration variables how would it be done without using python built in functions like

zip()
, or
list comprehensions
? Some basic functions are allowed like len.

I have tried making this work with this code:

list1 = [1,2,3]
list2 = [4,5,6]
list3 = []

def function():
for i,y in (list1, list2):
total = i * y
list3.append(total)
return list3
print(function())


But I get an error


"ValueError: too many values to unpack (expected 2)".


I am trying to get a new list which will multiply the 1st element with the 1st element in the other list and so on.

Answer

If your two arrays are equal by size. Below answer is right

    list1 = [2,2,2]
    list2 = [3,3,3]

    def function():
        for i in range(len(list1)):
            print(list1[i]*list2[i])
    print(function())

But best practice is use to zip method

for i, j in zip(list1, list2):
    print(i * j)
Comments