Python | Merge first and last elements separately in a list

Given a list of lists, where each sublist consists of only two elements, write a Python program to merge the first and last element of each sublist separately and finally, output a list of two sub-lists, one containing all first elements and other containing all last elements.

Examples:

Input : [['x', 'y'], ['a', 'b'], ['m', 'n']]
Output : [['x', 'a', 'm'], ['y', 'b', 'n']]

Input : [[1, 2], [3, 4], [5, 6], [7, 8]]
Output : [[1, 3, 5, 7], [2, 4, 6, 8]]

 
Approach #1 : List comprehension and zip



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Merge first and last
# elements separately in a list of lists
  
def merge(lst):
      
    return [list(ele) for ele in list(zip(*lst))]
      
# Driver code
lst = [['x', 'y'], ['a', 'b'], ['m', 'n']]
print(merge(lst))

chevron_right


Output:

[['x', 'a', 'm'], ['y', 'b', 'n']]

 
Approach #2 : Using Numpy array

First convert the given list to numpy array and then return transpose of the array, and finally convert the array to list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to Merge first and last
# elements separately in a list of lists
import numpy as np
  
def merge(lst):
    arr = np.array(lst)
    return arr.T.tolist()
      
# Driver code
lst = [['x', 'y'], ['a', 'b'], ['m', 'n']]
print(merge(lst))

chevron_right


Output:

[['x', 'a', 'm'], ['y', 'b', 'n']]


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.