Python | Merge list elements
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 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']
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 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'
Last Updated on November 13, 2021 by admin