Nothing Special   »   [go: up one dir, main page]

Open In App

Python – Merge list elements

Last Updated : 10 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Merging list elements is a common task in Python. Each method has its own strengths and the choice of method depends on the complexity of the task. This is the simplest and most straightforward method to merge elements. We can slice the list and use string concatenation to combine elements.

Python
a = list('geeksforgeeks')

# Merge 'f', 'o', 'r' into 'for'
b = [''.join(a[5:8])]  # store 'for' in a variable 

a = a[:5] + b + a[8:]

print(a)

Output
['g', 'e', 'e', 'k', 's', 'for', 'g', 'e', 'e', 'k', 's']

Other methods to merge list elements in python are:

Using List Comprehension

List comprehension is a compact way to merge elements based on specific positions or conditions.

Python
a = list('geeksforgeeks')

# Define the positions to merge in the list
merge_positions = [(0, 5), (5, 8), (8, 13)]

# Use list comprehension to merge elements into words
result = [''.join(a[start:end]) for start, end in merge_positions]

# Print the updated list
print(result)

Output
['geeks', 'for', 'geeks']

Using itertools.groupby

The itertools.groupby function groups consecutive elements together, which can be useful when merging similar characters or adjacent elements into words.

Python
import itertools
a = list('geeksforgeeks')

# Group the characters and merge consecutive ones into words
grouped = [''.join(group) for key, group in itertools.groupby(a)]

# Print the updated list
print(grouped)

Output
['g', 'ee', 'k', 's', 'f', 'o', 'r', 'g', 'ee', 'k', 's']

Using zip() and join()

If we want to merge alternate elements or pair elements together, we can use zip() along with join().

Python
a = list('geeksforgeeks')
# Merge 'g' and 'e', 'e' and 'k', etc.
merged = [''.join(x) for x in zip(a[::2], a[1::2])]

# Print the updated list
print(merged)

Output
['ge', 'ek', 'sf', 'or', 'ge', 'ek']

Using reduce() from functools

The reduce() function from the functools module allows us to perform a cumulative operation on the list, which can be used for merging.

Python
from functools import reduce

a = list("geeksforgeeks")

# Use reduce to merge all elements into a single string
merged = reduce(lambda x, y: x + y, a)

# Print the merged string
print(merged)

Output
geeksforgeeks

Next Article

Similar Reads

three90RightbarBannerImg