Pratyush Tallapragada Pratyush Tallapragada - 9 months ago 41
Python Question

Insert elements in lists under array python

I have a array consisting of tuples.

Data = [('1234', 'abcd'), ('5678', 'efgh')]

I now have another set of variables in an array:

add = ["#happy", "#excited"]

I'm trying to append 'add' to 'Data' in the same order such that the output should look like:

data_new = [('1234', 'abcd', '#happy'), ('5678', 'efgh',"#excited")]

Is that possible?


You can use list comprehension with enumerate():

>>> Data = [('1234', 'abcd'), ('5678', 'efgh')]
>>> add = ['#happy', '#excited']
>>> [x + (add[i],) for i,x in enumerate(Data)]
[('1234', 'abcd', '#happy'), ('5678', 'efgh', '#excited')]

Note that a common pythonic way to solve this type of problem is with zip(), but it doesn't immediately give the desired output for your example because you end up with nested tuples:

>>> zip(Data,add) # or list(zip(Data,add)) in Python3
[(('1234', 'abcd'), '#happy'), (('5678', 'efgh'), '#excited')]