python: Insert elements into tuples inside of list of tuples

Viewed 306

I have two lists. One list of tuples containing two elements, another containing only strings.

What is the best way to combine these in this way:

list1 = [('1','2'), ('3','4')]
list2 = ['one','two']

expected_result = [('1','2','one'), ('3','4','two')]

I am stuck on something like:

result = [elt+(list2[0],) for elt in list1]

However, I'm not sure if it's possible to iterate 2 lists inside of one list comprehension at the same time. Having a bit of a brain fart here. any help would be appreciated.

Bonus points if it fits on one line (list comprehension style)!

2 Answers

You can zip() the two lists together. This will give you elements like (('1', '2'), 'one'). This assumes the lists are the same length. Then in a list comprehension make a new tuple from those either by concating them, or spreading the first into tuple as below:

list1 = [('1','2'), ('3','4')]
list2 = ['one','two']

[(*t, word) for t, word in zip(list1, list2)]
# [('1', '2', 'one'), ('3', '4', 'two')]

alternatively:

[t + (word,) for t, word in zip(list1, list2)]

List comprehension style solution (one liner)

list1 = [('1','2'), ('3','4')]
list2 = ['one','two']

new_lst = [ list1[i]+(list2[i],) for i in range(len(list1))]
print(new_lst)

>> [('1', '2', 'one'), ('3', '4', 'two')]

Related