hylaeus
hylaeus

Reputation: 255

loop through two list and extend one list by a value in the other list

I want to extend a list in lists by the value of another list:

list1 = [['a', 'a'], ['b','b'], ['c','c']]
list2 = [1,2,3]

I would like this:

list3 = [['a','a',1], ['b','b',2], ['c','c',3]]

Thank you for your help.

Upvotes: 0

Views: 142

Answers (2)

Matt
Matt

Reputation: 3741

[x+[y] for x,y in zip(list1,list2)]

zip(list1,list2) will give you a list of tuple pairs:

[(['a', 'a'], 1), (['b', 'b'], 2), (['c', 'c'], 3)]

The rest is a list comprehension. It takes each of those tuples and concatenates the zeroth element with the first element. All of these are then returned as a list.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

>>> [x + [y] for x, y in zip(list1, list2)]
[['a', 'a', 1], ['b', 'b', 2], ['c', 'c', 3]]

Upvotes: 4

Related Questions