Open In App

Python | Merge list elements

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. 

Method #1 : Using join() + List Slicing The join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality. 

Python3




# Python3 code to demonstrate
# merging list elements
# using join() + list slicing
 
# initializing list 
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using join() + list slicing
# merging list elements
test_list[5 : 8] = [''.join(test_list[5 : 8])]
 
# printing result
print ("The list after merging elements : " +  str(test_list))


Output:

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']

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 res list 

Method #2 : Using reduce() + lambda + list slicing The task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only 
 

Python




# Python code to demonstrate
# merging list elements
# using reduce() + lambda + list slicing
 
# initializing list 
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using reduce() + lambda + list slicing
# merging list elements
test_list[5 : 8] = [reduce(lambda i, j: i + j, test_list[5 : 8])]
 
# printing result
print ("The list after merging elements : " +  str(test_list))


Output:

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']

Method #3 : Using + operator and del

This approach uses the += operator to concatenate the elements in the list, and the del statement to remove the merged elements.

Python3




# Initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# Merging elements using the += operator
test_list[5] += ''.join(test_list[6:8])
 
# Removing merged elements
del test_list[6:8]
 
# Printing the merged list
print(test_list)
# This code is contributed by Edula Vinay Kumar Reddy


Output

['I', 'L', 'O', 'V', 'E', 'GFG']

Time complexity: O(n) ( To join all elements in worst case )

Auxiliary space: O(n) , since we are creating a new string to hold the concatenated elements.

Using the Map and Lambda Functions:

Another way to merge the elements of a list is to use the map function in combination with a lambda function. The map function applies the lambda function to each element in the list, and the lambda function concatenates the elements using the + operator.

Python3




# Initializing list
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Merging elements using map and lambda
result = ''.join(map(lambda x: x, test_list[5:8]))
 
# Replacing merged elements with the result
test_list[5:8] = [result]
 
# Printing the merged list
print("The list after merging elements : " + str(test_list))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']

This approach has a time complexity of O(n) and an auxiliary space of O(n), where n is the number of elements in the list.

Method #5 : Using  a for loop

Python3




test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
print ("The original list is : " + str(test_list))
merged = ""
for i in range(5, 8):
    merged += test_list[i]
test_list[5 : 8] = [merged]
print ("The list after merging elements : " +  str(test_list))
#This code is contributed by Jyothi pinjala.


Output

The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'V', 'E', 'GFG']

Time complexity: O(n)
Auxiliary Space: O(n)

Method #6:  Using heapq:

  1. Initialize the input list test_list.
  2. Create an empty string merged to store the merged elements.
  3. Use a for loop to iterate over the elements from indices 5 to 7 (exclusive) of test_list and concatenate them into the merged string.
  4. Replace the elements from indices 5 to 7 with the merged string using slicing.
  5. Print the updated list.

Python3




import heapq
 
test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
print("The original list is:", test_list)
 
# Merge elements from indices 5 to 7
merged = "".join(heapq.nlargest(3, test_list[5:8]))
test_list[5:8] = [merged]
 
print("The list after merging elements:", test_list)
#This code is contributed by Vinay Pinjala.


Output

The original list is: ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements: ['I', 'L', 'O', 'V', 'E', 'GGF']

Time Complexity: O(n), where n is the length of the input list test_list. This is because the for loop iterates over the elements from indices 5 to 7 (exclusive), which takes O(1) time, and the slicing operation takes constant time.

Auxiliary Space:  O(n), where n is the length of the input list test_list. This is because we are creating a string to store the merged elements, which takes O(n) space.



Previous Article
Next Article

Similar Reads

Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
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', '
2 min read
Python | Merge list of tuple into list by joining the strings
Sometimes, we are required to convert list of tuples into a list by joining two element of tuple by a special character. This is usually with the cases with character to string conversion. This type of task is usually required in the development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed. L
6 min read
Python Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5->7->17->13->11 and second is 12->10->2->4->6, the first list should become 5->12->7->10->17->2->13->4->11->6 and second list should become empty. The
3 min read
Merge the elements in subarray of all even elements of the Array
Given an array arr[] containing N numbers, the task is to merge the subarray of consecutive even numbers by replacing all consecutive even numbers by the first even element of that subarray.Note: A series of even integers are said to be consecutive if there are at least three even numbers in the given series. Therefore, merge elements in subarray w
9 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Python | Merge elements of sublists
Given two lists containing sublists, the task is to merge elements of sublist of two lists in a single list. Examples: Input: list1 = [[1, 20, 30], [40, 29, 72], [119, 123, 115]] list2 = [[29, 57, 64, 22], [33, 66, 88, 15], [121, 100, 15, 117]] Output: [[1, 20, 30, 29, 57, 64, 22], [40, 29, 72, 33, 66, 88, 15], [119, 123, 115, 121, 100, 15, 117]] M
3 min read
Python Program to Merge a Matrix By the Elements of First Column
Given a Matrix, perform merge on the basis of the element in the first column. Input : test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"], [4, "cs"], [3, "best"]] Output : [[4, 'geeks', 'CS', 'cs'], [3, 'Gfg', 'best']] Explanation : 4 is paired with geeks, CS and cs hence are merged into 1 row. Input : test_list = [[4, "geeks"], [3, "Gfg"], [4, "CS"]
5 min read
Python | Merge two lists into list of tuples
Given two lists, write a Python program to merge the two lists into list of tuples. Examples: Input : list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] Output : [(1, 'a'), (2, 'b'), (3, 'c')] Input : list1 = [1, 2, 3, 4] list2 = [ 1, 4, 9] Output : [(1, 1), (2, 4), (3, 9), (4, '')]Approach #1: Naive Here we will merge both the list into a list of tuples us
6 min read
Python | Ways to merge strings into list
Given n strings, the task is to merge all strings into a single list. While developing an application, there come many scenarios when we need to operate on the string and convert it as some mutable data structure, say list. There are multiple ways we can convert strings into list based on the requirement. Let's understand it better with help of exa
4 min read
three90RightbarBannerImg