Mpizos Dimitris
Mpizos Dimitris

Reputation: 4991

Appending in lists of list

I am having the following lists:

listA = [[1,1,1,1],[1,1,1,1],[1,1,1,1],[1,1,1,1]]
listB = [1,2,3,4]

and I want:

listC = [[1, 1, 1, 1, 1], [1, 1, 1, 1, 2], [1, 1, 1, 1, 3], [1, 1, 1, 1, 4]]

I am using the following code:

for i in range(len(listA)):
     listA[i].append(listB[i])

The result is ok but I want to do that in one line using list comprehension(if possible, or another more elegant way). I can understand a simple list comprehension but not more complicated.

Upvotes: 2

Views: 68

Answers (2)

lejlot
lejlot

Reputation: 66805

List comprehension is not used to alternate (modify) existing objects, but to create new ones, you can do it for example through zipping your elements

listA = [a + [b] for a, b in zip(listA, listB)]

However notice that this actually is linear in time, it destroys the old listA and creates the new one, while your original code is more efficient as it only modifies the listA object.

The most efficient and pythonic way would be to connect these two and call

for a, b in zip(listA, listB):
    a.append(b)

Upvotes: 5

serge-sans-paille
serge-sans-paille

Reputation: 2139

This should do the trick:

[x + [y] for x, y in zip(listA, listB)]

Upvotes: 7

Related Questions