Skip to content
Advertisement

How to use i right in a for loop?

I have 3 lists and I need to calculate for each i the product of first list i, second list i and third list len-(i+1).

I tried to make a for loop which will do it for each i and I wrote this

i = 0
for i in list:
    smh=list1[i]*list2[i]*list3[len-(i+1)]
    print(smh)
    i = i + 1

But it says in the second line “‘type’ object is not iterable” How can I make it work?

Advertisement

Answer

Here you would need to get a little fancy and use the zip() function to properly iterate over all the members of the list.

here is some information on it: https://www.geeksforgeeks.org/python-iterate-multiple-lists-simultaneously/

list1 = [1,2]
list2 = [3,4]
list3 = [4,5]
for (a, b, c) in zip(list1, list2, reversed(list3)):
   smh = a*b*c
   print(smh)

Output: 15, 32.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement