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]
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.
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.
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]
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
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):])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With