Convert list of strings to list of tuples in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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)]
raja
Published on 20-May-2020 14:28:48
Advertisements