Reputation: 19
Hi i want to generate from lys1 and lys2 a new list called "lys3" that is the length of 3 that contains the (first value of lys1 * second value of lys2), (second value of lys1 * third value of lys2), (third value of lys1 * fourth value of lys2) using a loop.
lys1 = [5,6,2,9]
lys2 = [3,8,3,6]
lys3 = [i * j for i in lys1 for j in lys2]
print(lys3)
this is so far the logistics i've been able to figure out,
Upvotes: 0
Views: 41
Reputation: 152647
You should use zip
if you want to iterate over multiple iterables simultaneously. In your case you should slice away the first element of the second iterable so you have the desired "offset" between the first and second list:
[i * j for i, j in zip(lys1, lys2[1:])]
What you did was actually a double loop that iterated over each element in the second list for each element in the first list. Roughly equivalent to:
for i in lys1:
for j in lys2:
...
Which produces 16 elements.
Upvotes: 1