0

How to efficiently merge two lists efficiently? Following is the code which gives incorrect results. Not sure. Why?

a = [[]] * 5
b = [[1], [] , [], [2], []]
for i in range(0, len(a)):
    if b[i]:
        a[i] += b[i]

Expected output:

[[1], [], [], [2], []]

Acutal output:

[[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]

Result can be corrected by rewriting a[i] += b[i] to a[i] = a[i] + b[i]. However, I believe it would highly inefficient as it will result in creating a whole new list. FYI, each list will traversed a large numbers to need to be cache friendly if possible.

letsBeePolite
  • 2,183
  • 1
  • 22
  • 37
  • 1
    by `a=[[]]*5` you are just creating same copy of of list. do it explicitly like `[[] for _ in range(5)]` – Eular Mar 21 '17 at 19:49

1 Answers1

1

As can be seen in the duplicate question, you're just referencing the same list copy for each element in a. You could also do this to get your desired output:

>>> [x + y for x, y in zip(a, b)]
[[1], [], [], [2], []]
blacksite
  • 12,086
  • 10
  • 64
  • 109
  • 1
    OP asked for an efficient one. Your suggested solution requires the creation of a new list. Maybe this will align more with desire of OP `for i in range(0, len(a)): a[i].extend(b[i])` – letsBeePolite Mar 21 '17 at 19:56
  • That works, too. My one-liner's not necessarily "inefficient," however. Depends on what your definition of the term is :) – blacksite Mar 21 '17 at 19:58