Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math operations with lists using integers from nested lists

I have:

List1 = [100, 200, 300]

List2 = [[34,35,36],[0,1,2,3],[0,1,2]]

How can I sum each element of List1 with each element inside each list in List2?

I want:

List3 = [[134,135,136],[200,201,202,203],[300,301,302]]

I tried doing something along the lines of:

for i in List2:
    [sum(x) for x in zip(List1, i)] 

but I'm not getting the right answers.

Thanks in advance.

like image 981
Mike Issa Avatar asked Jan 26 '26 00:01

Mike Issa


1 Answers

If you want to use list comprehension(s), you could write:

>>> [[x + a for a in lst] for x, lst in zip(List1, List2)]
[[134, 135, 136], [200, 201, 202, 203], [300, 301, 302]]

(This assumes that both lists are the same length; if not you may want to use zip_longest from the itertools library to pad out the shorter list.)

like image 137
Alex Riley Avatar answered Jan 27 '26 14:01

Alex Riley