Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 830
Mpizos Dimitris Avatar asked Dec 05 '25 23:12

Mpizos Dimitris


1 Answers

This should do the trick:

[x + [y] for x, y in zip(listA, listB)]
like image 188
serge-sans-paille Avatar answered Dec 07 '25 14:12

serge-sans-paille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!