0

We have two lists list1 = [10,30,50], list2 = [2,4,6], and we want the output [10,2,30,4,50,6] (as opposed to [10,30,50,2,4,6], which is easier to generate). The lists could be very long so the manual solution list1[0] + list2[0] + list1[1] + ... is not feasible for us.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Canovice
  • 9,012
  • 22
  • 93
  • 211

3 Answers3

5

zip() grabs one item at a time from each list and pairs them up:

>>> list(zip(list1, list2))
[(1, 2), (3, 4), (5, 6)]

You can then use a second loop to flatten the pairs:

>>> [item for pair in zip(list1, list2) for item in pair]
[1, 2, 3, 4, 5, 6]

Note that if the lists are different lengths zip() will ignore the extra items in the longer one.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

In case the lists are of integers, as appearing in the question you can simply combine the two lists, and then sort them

list1.extend(list2)
sorted(l1)
Prophet
  • 32,350
  • 22
  • 54
  • 79
  • perhaps this is a bad example using integers because our actual list is of strings, the point is that the order of the lists matter. we cannot simply sort – Canovice Aug 24 '21 at 20:55
  • 3
    Well, you didn't mention that in the question. – Prophet Aug 24 '21 at 20:56
0
def sortLists(list1, list2):
    return sorted(list1+list2)
print(sortLists([1,2,5], [3,4]))

The output would be:

[1,2,3,4,5]
Arka Mukherjee
  • 2,083
  • 1
  • 13
  • 27