Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interleaving Lists in Python [duplicate]

Tags:

python

list

I have two lists:
[a, b, c] [d, e, f]
I want:
[a, d, b, e, c, f]

What's a simple way to do this in Python?

like image 284
beary605 Avatar asked Jun 20 '12 17:06

beary605


4 Answers

Here is a pretty straightforward method using a list comprehension:

>>> lists = [['a', 'b', 'c'], ['d', 'e', 'f']]
>>> [x for t in zip(*lists) for x in t]
['a', 'd', 'b', 'e', 'c', 'f']

Or if you had the lists as separate variables (as in other answers):

[x for t in zip(list_a, list_b) for x in t]
like image 169
Andrew Clark Avatar answered Nov 01 '22 18:11

Andrew Clark


One option is to use a combination of chain.from_iterable() and zip():

# Python 3:
from itertools import chain
list(chain.from_iterable(zip(list_a, list_b)))

# Python 2:
from itertools import chain, izip
list(chain.from_iterable(izip(list_a, list_b)))

Edit: As pointed out by sr2222 in the comments, this does not work well if the lists have different lengths. In that case, depending on the desired semantics, you might want to use the (far more general) roundrobin() function from the recipe section of the itertools documentation:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
like image 21
Sven Marnach Avatar answered Nov 01 '22 17:11

Sven Marnach


This one works only in python 2.x, but will work for lists of different lengths:

[y for x in map(None,lis_a,lis_b) for y in x]
like image 25
Ashwini Chaudhary Avatar answered Nov 01 '22 19:11

Ashwini Chaudhary


You could do something simple using built in functions:

sum(zip(list_a, list_b),())
like image 26
sblom Avatar answered Nov 01 '22 18:11

sblom