- Related Questions & Answers
- C program to find the length of a string?
- C Program to Check if a Given String is a Palindrome?
- Concatenate a string given number of times in C++ programming
- Sibling of a list element in JavaScript?
- Sum of the nodes of a Singly Linked List in C Program
- How to convert an OutputStream to a Writer in Java?
- How to convert a String to an InputStream object in Java?
- Print the string after the specified character has occurred given no. of times in C Program
- Print first k digits of 1/n where n is a positive integer in C Program
- C++ Program string class and its applications?
- To count Vowels in a string using Pointer in C++ Program
- 5 Different methods to find the length of a string in C++?
- 10 Interesting Python Cool Tricks
- howdoi in Python
- How to print without newline in Python?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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)

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]

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.

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)

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]

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.

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)

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]

Advertisements