Convert list of string into sorted list of integer in Python

PythonServer Side ProgrammingProgramming

Analysing data using python can bring us scenario when we have to deal with numbers represented as strings. In this article we will take a list which has numbers present as strings and we need to convert then to integers and then represent them in a sorted manner.

With map and sorted

In this approach we apply the int function to every element of the list using map. Then we apply the sorted function to the list which sorts the numbers. It can handle negative numbers also.

Example

 Live Demo

listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Use mapp
listint = map(int, listA)
# Apply sort
res = sorted(listint)
# Result
print("Sorted list of integers: \n",res)

Output

Running the above code gives us the following result −

Given list :
['54', '21', '-10', '92', '5']
Sorted list of integers:
[-10, 5, 21, 54, 92]

With int and sort

In this approach we apply the int function by using a for loop and store the result into a list. Then the sort function is applied to the list. The final result shows the sorted list.

Example

 Live Demo

listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = [int(x) for x in listA]
# Apply sort
res.sort()
# Result
print("Sorted list of integers: \n",res)

Output

Running the above code gives us the following result −

Given list :
['54', '21', '-10', '92', '5']
Sorted list of integers:
[-10, 5, 21, 54, 92]

With sorted and int

This approach is similar to above except that we apply int function through a for loop and enclose the result in the sorted function. It is a single expression which gives us the final result.

Example

 Live Demo

listA = ['54', '21', '-10', '92', '5']
# Given lists
print("Given list : \n", listA)
# Convert to int
res = sorted(int(x) for x in listA)
# Result
print("Sorted list of integers: \n",res)

Output

Running the above code gives us the following result −

Given list :
['54', '21', '-10', '92', '5']
Sorted list of integers:
[-10, 5, 21, 54, 92]
raja
Published on 20-May-2020 14:24:06
Advertisements