While manipulating data with python, we may come across a list which has numbers as strings. Further we may want to convert the list of strings into tuples. Of course the given strings are in a particular format of numbers.
With map and eval
We will use the map function to apply eval on every element of the list. Then store the final element as a list.
Example
listA = ['21, 3', '13, 4', '15, 7'] # Given list print("Given list : \n", listA) # Use eval res = list(map(eval, listA)) # Result print("List of tuples: \n",res)
Output
Running the above code gives us the following result −
Given list : ['21, 3', '13, 4', '15, 7'] List of tuples: [(21, 3), (13, 4), (15, 7)]
With map and split
In this approach we use the split function which will separate the elements with comma into two different elements. Next we apply the tuple function to create tuples containing the elements as pairs.
Example
listA = ['21, 3', '13, 4', '15, 7'] # Given list print("Given list : \n", listA) # Use split res = [tuple(map(int, sub.split(', '))) for sub in listA] # Result print("List of tuples: \n",res)
Output
Running the above code gives us the following result −
Given list : ['21, 3', '13, 4', '15, 7'] List of tuples: [(21, 3), (13, 4), (15, 7)]