ajesamann
ajesamann

Reputation: 7780

How to methodically join two lists?

So basically I have two lists in python, I want to join them together but in a certain way. I want them to be intertwined, I guess. Here’s an example.

List_a = [1, 2, 3]

List_b = [4, 5, 6]

Joined_Lists = [1, 4, 2, 5, 3, 6]

I want the joined list to be the lists combined together, but by inserting an item from list b every other one. I hope I explained this somewhat decent, lol.

Upvotes: 0

Views: 105

Answers (4)

alani
alani

Reputation: 13079

The convenient way to do it is clearly the [x for sublist in zip(List_a, List_b) for x in sublist] originally mentioned by DarrylG (although possibly with a different variable name, as zip yields tuples rather than lists). But more for sake of curiosity than anything, here is an alternative:

import itertools

def intertwine(*lists):
    return list(next(i) for i in itertools.cycle(iter(x) for x in lists))

The unusual thing about this example is that the for i in itertools.cycle(...) is an infinite loop, but the next(i) can raise StopIteration when one of the iterators which it yields is exhausted, and then the overall iterator (argument to list) will treat it in the same way as if the for i in ... loop had done the same.

So it gives:

>>> intertwine([1,2,3], [4,5,6])
[1, 4, 2, 5, 3, 6]

Note that the superficially equivalent list comprehension:

[next(i) for i in itertools.cycle(iter(x) for x in lists)]

would not work - an explicit StopIteration will be raised in the user code.

Upvotes: 1

karakfa
karakfa

Reputation: 67467

just to add to the existing (better) solutions, noting that this is essentially a transpose operation

> np.array(List_a+List_b).reshape(2,3).transpose().reshape(1,6)

array([[1, 4, 2, 5, 3, 6]])

Upvotes: 0

kaya3
kaya3

Reputation: 51034

Here's a way to do it with slice assignment, assuming the lists are either equal length, or a is 1 element longer than b:

def alternating(a, b):
    n = len(a) + len(b)
    out = [None] * n
    out[::2] = a
    out[1::2] = b
    return out

Examples:

>>> alternating([1, 2, 3], [4, 5, 6])
[1, 4, 2, 5, 3, 6]
>>> alternating([1, 2, 3, 4], [5, 6, 7])
[1, 5, 2, 6, 3, 7, 4]

Upvotes: 2

donkopotamus
donkopotamus

Reputation: 23176

This can be done with a comprehension:

def interleave(*iterables):
    return [x for y in zip(*iterables) for x in y]

Then

>>> interleave([1,2,3], [4,5,6])
[1, 4, 2, 5, 3, 6]
>>> interleave([1,2,3], [4,5,6], [7,8,9,10])
[1, 4, 7, 2, 5, 8, 3, 6, 9]

Note that this interleaves until the first iterable is exhausted.

Upvotes: 2

Related Questions