Htet
Htet

Reputation: 159

How to merge different type of list as one in Python

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

Answers (3)

Prafull kadam
Prafull kadam

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

dawg
dawg

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

ppasler
ppasler

Reputation: 3729

You may use zip and list comprehension:

list_A = [('Text1',2,3),('Text2',2,45),('Text3',2,23),('Text4',2,0)]
list_B = [7,3,3,9]

print [x + (y,) for x, y in zip(list_A, list_B)]

Note: x + y fails, as tuple and int can't be concatenated

Upvotes: 1

Related Questions