Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interleave two lists of different length?

Tags:

python

I'm quite new to Python and I am still having a hard time actually using the language itself into my program. Here's what I have so far:

# Purpose: 'twolists' = takes 2 lists, & returns a new list containing
# alternating elements of lists. 
# Return = final_list
# Parameter = list1, list2

def twolists(list1, list2): # don't forget to return final_list
    alt_list = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(# ? ):
        # append one thing from list1 to alt_list - How?
        # append one thing from list2 to alt_list - How?

Now the program is supposed to yield outputs like these:

outcome = twolists([ ], ['w', 'x', 'y', 'z'])
print(outcome)
['w', 'x', 'y', 'z']

outcome = twolists([0, 1], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x']

outcome = twolists([0, 1], ['w', 'x', 'y', 'z'])
print(outcome)
[0, 'w', 1, 'x', 'y', 'z']

outcome = twolists([0, 1, 2, 3], ['w', 'x'])
print(outcome)
[0, 'w', 1, 'x', 2, 3]
like image 895
FelixF Avatar asked Jan 11 '18 04:01

FelixF


People also ask

How do you interleave two lists in Python?

chain() + zip() zip() can be used to link both the lists and then chain() can used to perform the alternate append of the elements as desired.

How do you interleave three lists in Python?

To interleave multiple lists of the same length in Python, we can use list comprehension and zip . We have 3 lists l1 , l2 , and l3 . And then we put them into the lists list. Then to interleave all the lists, we call zip with all the lists in lists as arguments.


3 Answers

This composes a list comprehension using zip_longest from itertools (which is part of the standard library) to interleave items from both lists into a tuple, which by default uses None as the fillvalue.

This also uses chain also from itertools to flatten the list.

Finally it filters the None items from the list:

from itertools import chain, zip_longest
def twolists(l1, l2):
    return [x for x in chain(*zip_longest(l1, l2)) if x is not None]

Or as recommended from @EliKorvigo, use itertools.chain.from_iterable for iterating lazily:

def twolists(l1, l2):
    return [x for x in chain.from_iterable(zip_longest(l1, l2)) if x is not None]
Testing
In [56]: twolists([0, 1], ['w', 'x'])
Out[56]: [0, 'w', 1, 'x']

In [57]: twolists([0, 1], ['w', 'x', 'y', 'z'])
Out[57]: [0, 'w', 1, 'x', 'y', 'z']

In [74]: twolists([0, 1, 2, 3], ['w', 'x'])
Out[74]: [0, 'w', 1, 'x', 2, 3]
like image 159
salparadise Avatar answered Oct 02 '22 18:10

salparadise


def twolists(list1, list2):
    newlist = []
    a1 = len(list1)
    a2 = len(list2)

    for i in range(max(a1, a2)):
        if i < a1:
            newlist.append(list1[i])
        if i < a2:
            newlist.append(list2[i])

    return newlist
like image 30
John Gordon Avatar answered Oct 02 '22 17:10

John Gordon


def CombineLists(lst1, lst2):
   return [item for x in zip(lst1,lst2) for item in x] + /
         (lst2[len(lst1):] if len(lst2)>len(lst1) else lst1[len(lst2):])
like image 31
Tomer Avatar answered Oct 02 '22 17:10

Tomer