0

My Question is as follows:

  1. I want to loop through a list and assign the current iterated index value to a variable.
  2. In the same step I want to add this values into a second list in wich are already values.
  3. like this I want to add (+) every value in the list with every value of the same index in the second list via a loop

This could be an output like: l1 = [1, 2, 3] l2 = [4, 5, 6]

l3 = [5, 7, 9]

This is the code I have so far:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = [44, 55, 66, 77, 88, 99, 11, 22, 33]
for x in new_list:
    new_x = x
print(new_x)    
my_new_numbers = [n + new_x for n in my_list]


print(my_new_numbers)

i know its probably nonsense what I wrote, I just was trying to change this code, that in fact does work:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_numbers = []

for x in my_list:
    my_new_numbers.append(x * x)
print(my_new_numbers)

Would like to have a solution only with basic operators and loops and lists, no import etc.

Thanks a lot

  • Welcome to SO! Why not `[sum(x) for x in zip(a, b)]` or `list(map(sum, zip(a, b)))`? – ggorlen Oct 18 '20 at 20:42
  • Thanks, no i want to make an addition like List1 = [1, 2, 3] ; List2 = [4, 5, 6] List1 + List2 = [5, 7, 9] – BenjaminDiLorenzo Oct 18 '20 at 20:44
  • In a way it does. What i especially wanted to find out: Can I iterate through a list, assign the current value to a variable and then in the same time iterate through a second list, using each assigned value (like every step) to make an addition of the values in each step of iteration. That means, can I process an addition by two iterating loops in which one loop outputs each step value to a variable to use that variable in the second iteration. You know what I mean? – BenjaminDiLorenzo Oct 18 '20 at 20:58
  • Yeah, that's exactly what the code above does although it may not be obvious. It's basically the point of `zip`: iterating through multiple iterables simultaneously. `for x, y in zip(a, b): # do something with x and y`. `list(zip("abc", "123"))` -> `[('a', '1'), ('b', '2'), ('c', '3')]`. – ggorlen Oct 18 '20 at 21:06

0 Answers0