Python | Convert string tuples to list tuples

Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to list of tuples. This kind of problem can have it’s occurrence in data science domain. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using eval() + list comprehension
This problem can be easily performed as one liner using the inbuilt function of eval(), which performs this task of string to tuple conversion and list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Converting string tuples to list tuples 
# using list comprehension + eval()
  
# Initializing list 
test_list = ["('gfg', 1)", "('is', 2)", "('best', 3)"]
  
# printing original list 
print("The original list is : " + str(test_list))
  
# Converting string tuples to list tuples 
# using list comprehension + eval()
res = [eval(ele) for ele in test_list]
  
# printing result
print("The list tuple after conversion : " + str(res))

chevron_right


Output :



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

 

Method #2 : Using eval() + map()
This task can also be performed using combination of above functions. The task performed by list comprehension above can be performed using map() in this method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Converting string tuples to list tuples 
# using map() + eval()
  
# Initializing list 
test_list = ["('gfg', 1)", "('is', 2)", "('best', 3)"]
  
# printing original list 
print("The original list is : " + str(test_list))
  
# Converting string tuples to list tuples 
# using map() + eval()
res = list(map(eval, test_list))
  
# printing result
print("The list tuple after conversion : " + str(res))

chevron_right


Output :

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


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.