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.
            Asked
            
        
        
            Active
            
        
            Viewed 153 times
        
    0
            
            
         
    
    
        John Kugelman
        
- 349,597
- 67
- 533
- 578
 
    
    
        Canovice
        
- 9,012
- 22
- 93
- 211
- 
                    https://en.wikipedia.org/wiki/Merge_algorithm – Brian61354270 Aug 24 '21 at 20:52
- 
                    thanks but I would like to avoid implementing my own merge algorithm, i assume there's an easier solution in python – Canovice Aug 24 '21 at 20:53
- 
                    concatenate and sort, or use `zip()` those are basically your options – Gillespie Aug 24 '21 at 20:55
- 
                    1Do you know that the lists can be sorted in this specific way, or could they be e.g. `[1,4,5]` and `[2,3,6]` and what should be the result in this case? – tobias_k Aug 24 '21 at 20:57
- 
                    Are both lists guaranteed to always be the same length? – Gillespie Aug 24 '21 at 20:58
- 
                    1yes will always be the same length – Canovice Aug 24 '21 at 20:58
- 
                    no the lists cannot be sorted - this was a bad example using integers.. – Canovice Aug 24 '21 at 20:59
3 Answers
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
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