Convert List of Tuples to List of Strings - Python
Last Updated :
20 Jan, 2025
The task is to convert a list of tuples where each tuple contains individual characters, into a list of strings by concatenating the characters in each tuple. This involves taking each tuple, joining its elements into a single string, and creating a new list containing these strings.
For example, given the list li = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')], the goal is to convert it into ['GEEKS', 'FOR', 'GEEKS'] by combining the characters in each tuple.
Using list comprehension
List comprehension combined with the join()
method is a efficient technique in Python for concatenating strings from an iterable, like a list of tuples. This technique allows us to iterate over each tuple in the list, join its elements into a single string and store the result in a new list.
Python
li = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
res = [''.join(i) for i in li]
print(res)
Output['GEEKS', 'FOR', 'GEEKS']
Explanation:
- List comprehension iterates over each tuple
i
in the list li
and for each tuple i
, ''.join(i)
concatenates all its characters into a single string join()
combines the characters of the tuple into a string without any separator.
Using map()
map() function in combination with the join() method is another efficient way to convert a list of tuples into a list of strings. This approach emphasizes a functional programming style, applying a transformation to each element in the list.
Python
li = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
res = list(map(lambda x: ''.join(x), li))
print(res)
Output['GEEKS', 'FOR', 'GEEKS']
Explanation:
map()
:This applies a function to each tuple in the list.lambda x: ''.join(x)
: This joins characters of each tuple into a single string.list()
:This converts the map
object into a list.
Using reduce ()
reduce() function from Python's functools module is a tool for applying a cumulative operation to the elements of an iterable. When combined with join(), it can be used to convert a list of tuples into a list of strings by iteratively concatenating the strings into a new list.
Python
from functools import reduce
li = [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
res = list(reduce(lambda acc, x: acc + [''.join(x)],li, []))
print(res)
Output['GEEKS', 'FOR', 'GEEKS']
Explanation:
reduce()
: This iteratively combines elements of li
into a single result, starting with an empty list ([]
).acc + [''.join(x)]:
This
converts the current tuple x
to a string using ''.join(x)
and appends it to the accumulator acc
.