Python | Merge Tuple String List values to String

Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension + join()
The combination of above functionalities can be used to achieve to solution of above task. In this, we get the character list using list comprehension and conversion task is performed by join().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Merge Tuple String List values to String
# using list comprehension + join()
  
# initialize list
test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
  
# printing original list
print("The original list : " + str(test_list))
  
# Merge Tuple String List values to String
# using list comprehension + join()
res =  [''.join(i) for i, j in test_list]
  
# printing result
print("The joined character list tuple element to string is : " + str(res))

chevron_right


Output :



The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]
The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]

 

Method #2 : Using map() + join() + lambda
The task performed by list comprehension in the above method can be performed by map() and lambda function can be used to construct the logic to achieve the solution to this task.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Merge Tuple String List values to String
# using map() + join() + lambda
  
# initialize list
test_list = [(['g', 'f', 'g'], 1), (['i', 's'], 2), (['b', 'e', 's', 't'], 3)]
  
# printing original list
print("The original list : " + str(test_list))
  
# Merge Tuple String List values to String
# using map() + join() + lambda
res = list(map(lambda sub : "".join(sub[0]), test_list))
  
# printing result
print("The joined character list tuple element to string is : " + str(res))

chevron_right


Output :

The original list : [([‘g’, ‘f’, ‘g’], 1), ([‘i’, ‘s’], 2), ([‘b’, ‘e’, ‘s’, ‘t’], 3)]
The joined character list tuple element to string is : [‘gfg’, ‘is’, ‘best’]



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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.