Python | Flatten Tuples List to String

Sometimes, while working with data, we can have a problem in which we need to perform interconversion of data. In this, we can have a problem of converting tuples list to a single String. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + join()
The combination of above functionalities can be used to perform this task. In this, we join all the individual string elements using join() and extraction of each element is done using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Flatten Tuples List to String
# using join() + list comprehension
  
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
  
# printing original tuples list
print("The original list : " + str(test_list))
  
# Flatten Tuples List to String
# using join() + list comprehension
res = ' '.join([idx for tup in test_list for idx in tup])
  
# printing result
print("Tuple list converted to String is : " + res)

chevron_right


Output :



The original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
Tuple list converted to String is : 1 4 6 5 8 2 9 1 10

 

Method #2 : Using chain() + join()
This is yet another method to perform this particular task. In this, we perform the task of extracting each of element of tuple list using chain() rather than list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Flatten Tuples List to String
# using chain() + join()
from itertools import chain
  
# initialize list of tuple
test_list = [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
  
# printing original tuples list
print("The original list : " + str(test_list))
  
# Flatten Tuples List to String
# using chain() + join()
res =  ' '.join(chain(*test_list))
  
# printing result
print("Tuple list converted to String is : " + res)

chevron_right


Output :

The original list : [('1', '4', '6'), ('5', '8'), ('2', '9'), ('1', '10')]
Tuple list converted to String is : 1 4 6 5 8 2 9 1 10


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.