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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.