Python: shortest way to interleave items from two lists

9

I'm trying to get the shortest way (character possible) to obtain List 3.

List 1 and List 2 are already given to me as arguments and are the same length.

l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']

And List 3 should look like (yes, it needs to be a list):

l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5]

Matias

Posted 2018-08-03T01:50:28.343

Reputation: 93

2Is your goal to literally output the specific list l3 = ['a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5] given l1 = [1, 2, 3, 4, 5] and l2 = ['a', 'b', 'c', 'd', 'e'] already assigned, or is the idea that l1 and l2 could be any two lists of the same length? – xnor – 2018-08-03T02:50:49.143

Answers

13

Zip and Sum

[*sum(zip(l2,l1),())]

Try it online!

Zips the two lists together then adds all the tuples to make one combined list. The zip only works if the lists are guaranteed to be the same size, otherwise it truncates the longer list.

Added the surrounding [* ] to transform it into a list as FryAmTheEggman suggests.

Jo King

Posted 2018-08-03T01:50:28.343

Reputation: 38 234

2If using Python 2, you can just use list instead of [* (...) ] for +3 bytes. – Erik the Outgolfer – 2018-08-03T09:47:03.007

6

Slice assignment

c=a*2
c[1::2]=a
c[::2]=b

This is three bytes longer than using Jo King’s solution c=[*sum(zip(b,a),())], but it’s nifty. It might be shorter situationally (I can’t think of where, though).

Lynn

Posted 2018-08-03T01:50:28.343

Reputation: 55 648