Roman
Roman

Reputation: 3241

combine two lists into one using one by one element

How to combine two lists into one using one by one element as follows:

list1 = ['a','c','e']

list2 = ['apple','carrot','elephant']

result = ['a', 'apple', 'c', 'carrot', 'e', 'elephant']

Trial

result = [(x,y) for x,y in zip(list1,list2)]
print result

But they are in tuples, any easier soultion is expected...

Upvotes: 1

Views: 2076

Answers (2)

tobias_k
tobias_k

Reputation: 82899

You can use a double-for-loop list comprehension:

>>> list1 = ['a','c','e']
>>> list2 = ['apple','carrot','elephant']
>>> [x for z in zip(list1, list2) for x in z]
['a', 'apple', 'c', 'carrot', 'e', 'elephant']

Upvotes: 9

inspectorG4dget
inspectorG4dget

Reputation: 113985

In [4]: list1 = ['a','c','e']

In [5]: list2 = ['apple','carrot','elephant']

In [6]: list(itertools.chain.from_iterable(zip(list1, list2)))
Out[6]: ['a', 'apple', 'c', 'carrot', 'e', 'elephant']

Upvotes: 4

Related Questions