10
\$\begingroup\$

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]
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Is 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? \$\endgroup\$
    – xnor
    Aug 3, 2018 at 2:50

2 Answers 2

13
\$\begingroup\$

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.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ If using Python 2, you can just use list instead of [* (...) ] for +3 bytes. \$\endgroup\$ Aug 3, 2018 at 9:47
7
\$\begingroup\$

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).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.