Sanidhay
Sanidhay

Reputation: 159

Combining two Python lists in an interleaved manner

I want to interleave two lists. For example:

arr1 = [1,2,3,4,5,6]
arr2 = [9,8,7,6]

I't like to get an output like

[1,9,2,8,3,7,4,6,5,6]

I have created the following script, but it's not working for some reason:

arr1 = [1,2,3,4,5,6]
arr2 = [9,8,7,6]
x = 0

for a in arr2:
    x = x + 2
    arr1.insert(x, a)

Where am I going wrong? I am not looking for random shuffling. I am using python2.x

Upvotes: 1

Views: 112

Answers (3)

Sede
Sede

Reputation: 61253

You can use zip_longest and chain.from_iterable from the itertools module:

>>> arr1 = [1,2,3,4,5,6]
>>> arr2 = [9,8,7,6]
>>> from itertools import chain, zip_longest
>>> [i for i in chain.from_iterable(zip_longest(arr1, arr2)) if i is not None]
[1, 9, 2, 8, 3, 7, 4, 6, 5, 6]

You need to use izip_longest instead of zip_longest in python-2.x

Upvotes: 3

Sanidhay
Sanidhay

Reputation: 159

I have figured out a different way to do this, without imports.

mylist = []
a = [1,2,3,4,5,6]
b = [9,8,7,6]
for x in range(max(len(a), len(b))):
    if x < len(a):
        mylist.append(a[x])
    if x < len(b):
        mylist.append(b[x])

Upvotes: 1

Back2Basics
Back2Basics

Reputation: 7806

if you actually want to shuffle them in a randomized fashion the key would be to combine them into one list and use shuffle().

from random import shuffle
import itertools as it

arr1 = [1,2,3,4,5,6]
arr2 = [9,8,7,6]
x = list(it.chain(arr1,arr2))
shuffle(x)
print(x)

EDIT question was updated to reflect the order desired wasn't random.

Upvotes: 0

Related Questions