How to Merge Elements in a Python Sequence?


Python Sequences includes Strings, Lists, Tuples, etc. We can merge elements of a Python sequence using different ways.

Merge Elements in a Python List

Example

The join() method is used to merge elements −

# List myList = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U'] # Display the List print ("List = " + str(myList)) # Merge items using join() myList[0 : 3] = [''.join(myList[0 : 3])] # Displaying the Result print ("Result = " + str(myList))

Output

List = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
Result = ['HOW', 'A', 'R', 'E', 'Y', 'O', 'U']

Merge Elements in a Python List using Lambda

To merge elements using Lambda, we will use the reduce() method. The reduce() is part of the functools module in Python. Let us first learn to install and use the functools module.

Install the functools module.

pip install functools

Use the functools module.

import functools

Example

Following is the code.

import functools # List myList = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U'] # Display the List print("List = " + str(myList)) # Merge items using Lambda myList[0: 3] = [functools.reduce(lambda i, j: i + j, myList[0: 3])] # Displaying the Result print("Result = " + str(myList))

Output

List = ['H', 'O', 'W', 'A', 'R', 'E', 'Y', 'O', 'U']
Result = ['HOW', 'A', 'R', 'E', 'Y', 'O', 'U']

Merge Elements in a Python List with for loop

Example

In this example, we will merge elements using for loop.

# List myList = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82'] # Display the List print("List = " + str(myList)) # Merge items myList = [myList[i] + " " + myList[i+1] for i in range(0, len(myList), 2)] # Displaying the Result print("Result = " + str(myList))

Output

List = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
Result = ['john 96', 'tom 90', 'steve 86', 'mark 82']

Merge Elements in a Python List with slice and zip()

Example

In this example, we will merge elements using the zip() method.

# List myList = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82'] # Display the List print("List = " + str(myList)) # Merge items with slice and zip() myList = [':'.join(item) for item in zip(myList[::2],myList[1::2])] # Displaying the Result print("Result = " + str(myList))

Output

List = ['john', '96', 'tom', '90', 'steve', '86', 'mark', '82']
Result = ['john:96', 'tom:90', 'steve:86', 'mark:82']

Updated on: 15-Sep-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements