user2160982
user2160982

Reputation: 189

Python two list lists shuffle

I have two list:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]

I need to get something like this:

c = [1, 5, 2, 6, 3, 7, 4, 8]

I use this solution:

c = list(reduce(lambda x, y: x + y, zip(a, b)))

Is there a better way to do this?

Upvotes: 2

Views: 359

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213233

Using List Comprehension:

>>> [x for tup in zip(a, b) for x in tup]
[1, 5, 2, 6, 3, 7, 4, 8]

The above nested list comprehension is equivalent to following nested for loops (Just in case you get confused):

result = []
for tup in zip(a, b):
    for x in tup:
        result.append(x)

Upvotes: 9

Pavel Anossov
Pavel Anossov

Reputation: 62908

Also viable:

list(sum(zip(a, b), ()))

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142146

Using chain:

from itertools import chain, izip
interweaved = list(chain.from_iterable(izip(a, b)))
# [1, 5, 2, 6, 3, 7, 4, 8]

Upvotes: 6

Related Questions