Method # 1: Using List Comprehension + join()
A combination of the above functions can be used to accomplish this task. In doing so, we concatenate all individual inline elements using join ()
and retrieve each element using a list.
# Python3 code to demonstrate how it works # Combine the list of tuples into a string # using join () + list comprehension # initialize the list of tuples test_list = [( ’1’ , ’ 4’ , ’6’ ), ( ’5’ , ’ 8’ ), ( ’2’ , ’ 9’ ), ( ’1’ , ’10’ )] # print the original list of tuples print ( "The original list:" + str (test_list)) # Combine the list of tuples into a string # using join () + list comprehension res = ’’ . join ([idx for tup in test_list for idx in tup]) # print result print ( "Tuple list converted to String is: " + res) |
code> 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 another method to accomplish this specific task. In this we perform the task of retrieving each element of the list of tuples using chain ()
rather than a list comprehension.
# Python3 demo code work # Combine the list of tuples into a string # using chain () + join () from itertools import chain # initialize the list of tuples test_list = [( ’1’ , ’ 4’ , ’6’ ), ( ’5’ , ’ 8’ ), ( ’2’ , ’ 9’ ), ( ’1’ , ’ 10’ )] # print the original list of tuples print ( " The original list: " + str (test_list)) # Combine the list of tuples into a string # using chain () + join () res = ’’ . join (chain ( * test_list)) # print result print ( "Tuple list converted to String is:" + res) |
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
Python | Flatten a list of tuples into a string Python functions: Questions
Python | Flatten a list of tuples into a string String Variables: Questions