Monday, November 18, 2024
Google search engine
HomeLanguagesPython | Merge first and last elements separately in a list

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




# 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))


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




# 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))


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




# Python3 program to Merge first and last
# elements separately in a list of lists
 
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']]
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments