Reputation: 159
I have a list with multiple values which looks like below:
list_A = [('Text1',2,3),('Text2',2,45),('Text3',2,23),('Text4',2,0)]
Let's say it contains 4 items with 3 variables in each. And I have another list with the same number of items, but one variable for each, which looks like this:
list_B = [7,3,3,9]
I've been trying to merge them, and the only thing I can get so far is:
zip(list_A, list_B)
>>[(('Text1',2,3),7), (('Text2',2,45),3), (('Text3',2,0),3), (('Text4',2,3),9)]
tuple(zip(list_A, list_B)
>>((('Text1',2,3),7), (('Text2',2,45),3), (('Text3',2,0),3), (('Text4',2,3),9))
The final result should be in this format:
new_list = [('Text1',2,3,7),('Text2',2,45,7),('Text3',2,23,7),('Text4',2,0,9)]
Upvotes: 0
Views: 69
Reputation: 208
Python tuples have a trait: they are immutable, but their values may change. This may happen when a tuple holds a reference to any mutable object, such as a list.
Tuple is immutable we can not modify it again: So we recreate this as follows:
list_A = [('Text1',2,3),('Text2',2,45),('Text3',2,23),('Text4',2,0)]
list_B = [7,3,3,9]
new_list = [(i[0]+(i[1],)) for i in zip(list_A, list_B)]
or
new_list = [tuple(list(i[0])+[i[1]]) for i in zip(list_A, list_B)]
new_list
[('Text1', 2, 3, 7), ('Text2', 2, 45, 3), ('Text3', 2, 23, 3), ('Text4', 2, 0, 9)]
Upvotes: 0
Reputation: 104092
Tuples can be added to form a new tuple, so you should form a tuple with the element from list_B:
>>> list_A = [('Text1',2,3),('Text2',2,45),('Text3',2,23),('Text4',2,0)]
>>> list_B = [7,3,3,9]
>>> [t+(e,) for t,e in zip(list_A, list_B)]
[('Text1', 2, 3, 7), ('Text2', 2, 45, 3), ('Text3', 2, 23, 3), ('Text4', 2, 0, 9)]
Or, in Python 3.5+ only, you can do:
>>> [(*t, e) for t, e in zip(list_A, list_B)]
[('Text1', 2, 3, 7), ('Text2', 2, 45, 3), ('Text3', 2, 23, 3), ('Text4', 2, 0, 9)]
Upvotes: 2