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
# 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)) |
[['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.
# 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)) |
[['x', 'a', 'm'], ['y', 'b', 'n']]
Recommended Posts:
- Python | Merge List with common elements in a List of Lists
- Python | Merge list elements
- Python | Merge list of tuple into list by joining the strings
- Python | List value merge in dictionary
- Python | Merge elements of sublists
- Python | Merge two lists into list of tuples
- Python | Ways to merge strings into list
- Python | Selective Merge in String list
- Python | Selective Merge list every Nth position
- Python | Merge two list of lists according to first element
- Python | Merge Python key values to list
- Python | Sorting list of lists with similar list elements
- Python | Replace elements in second list with index of same element in first list
- Python | Add list elements with a multi-list based on index
- Python | Indices of sorted list of list elements
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.


