Python | Merge first and last elements separately in a list
Last Updated :
17 Apr, 2023
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
def merge(lst):
return [ list (ele) for ele in list ( zip ( * lst))]
lst = [[ 'x' , 'y' ], [ 'a' , 'b' ], [ 'm' , 'n' ]]
print (merge(lst))
|
Output
[['x', 'a', 'm'], ['y', 'b', 'n']]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
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
import numpy as np
def merge(lst):
arr = np.array(lst)
return arr.T.tolist()
lst = [[ 'x' , 'y' ], [ 'a' , 'b' ], [ 'm' , 'n' ]]
print (merge(lst))
|
Output:
[['x', 'a', 'm'], ['y', 'b', 'n']]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list
Approach #3 : Using for loop + extend() method
Python3
lst = [[ 'x' , 'y' ], [ 'a' , 'b' ], [ 'm' , 'n' ]]
a = []
for i in lst:
a.extend(i)
x = []
y = []
for i in range ( 0 , len (a)):
if (i % 2 = = 0 ):
x.append(a[i])
else :
y.append(a[i])
res = []
res.append(x)
res.append(y)
print (res)
|
Output
[['x', 'a', 'm'], ['y', 'b', 'n']]
Share your thoughts in the comments
Please Login to comment...