1

I have a list which contains:

["('apple','banana')","('orange','cherry')"]

I want to remove the quotes from the list and convert it into a tuple I tried to use

tuple(list1)

But I am getting:

 ("('apple','banana')", "('orange','cherry')")

OR

I want the output to be:

('apple','banana'),('orange','cherry')

also this output could help:

[('apple','banana'),('orange','cherry')]
Vaibhav Borkar
  • 171
  • 2
  • 12
  • 5
    How did you get to produce such a list in the first place? `import ast` then `[ast.literal_eval(t) for t in inputlist]` will convert each element to a tuple, but you may want to avoid getting into this pickle in the first place. – Martijn Pieters Apr 27 '17 at 19:51
  • I have a list of cities in the format [a,b,c,d,.......]. I wanted to make a network of those cities which could be visited from any place, like from b to a, c to b, c to a and so on. To make such a network I needed a tuple. So I needed it to convert from list to tuple – Vaibhav Borkar Apr 27 '17 at 20:56

2 Answers2

1

You should use ast.literal_eval for this purpose, which is safer than eval.

>>> import ast
>>> x = ["('apple','banana')","('orange','cherry')"]
>>> [ast.literal_eval(i) for i in x]
[('apple', 'banana'), ('orange', 'cherry')]
brianpck
  • 8,084
  • 1
  • 22
  • 33
-2
In [1]: l = ["('apple','banana')","('orange','cherry')"]
In [2]: map(eval, l)
Out[2]: [('apple', 'banana'), ('orange', 'cherry')]
Aviad
  • 343
  • 1
  • 7