tayrix tayrix - 10 months ago 52
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

, 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
return list3

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 Source

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)):

But best practice is use to zip method

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