Convert list of tuples to list of strings in Python

PythonServer Side ProgrammingProgramming

During data processing using python, we may come across a list whose elements are tuples. And then we may further need to convert the tuples into a list of strings.

With join

The join() returns a string in which the elements of sequence have been joined by str separator. We will supply the list elements as parameter to this function and put the result into a list.

Example

 Live Demo

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
# Given list
print("Given list : \n", listA)
res = [''.join(i) for i in listA]
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given list :
[('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list:
['Mon', 'day', '7pm']

With map and join

We will take a similar approach as above but use the map function to apply the join method. Finally wrap the result inside a list using the list method.

Example

 Live Demo

listA = [('M','o','n'), ('d','a','y'), ('7', 'pm')]
# Given list
print("Given list : \n", listA)
res = list(map(''.join, listA))
# Result
print("Final list: \n",res)

Output

Running the above code gives us the following result −

Given list :
[('M', 'o', 'n'), ('d', 'a', 'y'), ('7', 'pm')]
Final list:
['Mon', 'day', '7pm']
raja
Published on 20-May-2020 14:36:49
Advertisements