0

Preface: Element-wise addition of 2 lists?

I want to write to code to have the following behavior:

[ 1, 1, ["Alpha"]]
+
[ 2, 2, ["Beta"] ]
||       ||     ||
\/       \/     \/
[3, 3, ["Alpha", "Beta"]]

in python. Is this possible without very messy comprehensions and mapping?

cs95
  • 379,657
  • 97
  • 704
  • 746
Erich
  • 1,902
  • 1
  • 17
  • 23
  • 2
    Voting to close as duplicate since the answers given (and the pythonic answers) are duplicates of the linked question. The short answer is `yes`, you can avoid maps/comprehension using loops. – Snakes and Coffee Jul 24 '17 at 21:13
  • I will also add, since no one has added this answer, that you can use reduce and a custom lambda for aggregating any number of weird data types. – Erich Sep 12 '19 at 19:25

3 Answers3

7
[a + b for a, b in zip(l1, l2)]
Luckk
  • 518
  • 3
  • 7
  • Indeed. I'd be interested to know if the OP thinks it's a "messy comprehension". – Eric Duminil Jul 24 '17 at 21:17
  • I believe in an older version of python that this did not work for custom defined classes, or that it at least didn't work for my use case because I tried this and it failed. I forget that use case now unfortunately, but this does now work, at least for my machine. – Erich Sep 12 '19 at 19:23
3

Yes, it is possible, though I'd think twice before calling list comprehensions messy. Pass operator.__add__ to map along with the two lists:

import operator
list(map(operator.__add__, l1, l2))
# [3, 3, ['Alpha', 'Beta']]
cs95
  • 379,657
  • 97
  • 704
  • 746
2

This solution uses list comprehensions, although they are, imo, far from messy. Also, it is pretty readable and doesn't require a library

a = [1, 1, ["ALPHA"]]
b = [2, 2, ["BETA"]]
c = [a[i]+b[i] for i in range(len(a))]
print(c)
Sam Craig
  • 875
  • 5
  • 16