Skip to content
Related Articles

Related Articles

Python | Convert mixed data types tuple list to string list

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 29 Nov, 2019

Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + tuple() + str() + generator expression
The combination of above functions can be used to perform this task. In this, we extract each tuple element using generation expression and perform the conversion using str(). The iteration to each tuple is done by list comprehension.




# Python3 code to demonstrate working of
# Convert tuple mixed list to string list
# using list comprehension + tuple() + str() + generator expression
  
# initialize list 
test_list = [('gfg', 1, True), ('is', False), ('best', 2)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Convert tuple mixed list to string list
# using list comprehension + tuple() + str() + generator expression
res = [tuple(str(ele) for ele in sub) for sub in test_list]
  
# printing result
print("The tuple list after conversion : " + str(res))

Output :

The original list : [('gfg', 1, True), ('is', False), ('best', 2)]
The tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]

 

Method #2 : Using map() + tuple() + str() + list comprehension
The combination of above functions can be used to perform this task. In this, we perform the task performed by generator expression above using map().




# Python3 code to demonstrate working of
# Convert tuple mixed list to string list
# using map() + tuple() + str() + list comprehension
  
# initialize list 
test_list = [('gfg', 1, True), ('is', False), ('best', 2)]
  
# printing original list 
print("The original list : " + str(test_list))
  
# Convert tuple mixed list to string list
# using map() + tuple() + str() + list comprehension
res = [tuple(map(str, sub)) for sub in test_list]
  
# printing result
print("The tuple list after conversion : " + str(res))

Output :

The original list : [('gfg', 1, True), ('is', False), ('best', 2)]
The tuple list after conversion : [('gfg', '1', 'True'), ('is', 'False'), ('best', '2')]


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!