Skip to content
Related Articles

Related Articles

Python | Ways to sort list of float values
  • Last Updated : 11 May, 2020

Given a list of float values, write a Python program to sort the list.

Examples:

Input: list = ['1.2', '.8', '19.8', '2.7', '99.8', '80.7']
Output: ['.8', '1.2', '2.7', '19.8', '80.7', '99.8']

Input: list = [12.8, .178, 1.8, 782.7, 99.8, 8.7]
Output: [0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

Let’s discuss different ways to solve this problem.

Method #1 :Using lambda




# Python code to sort list of decimal values
  
# List initialization
Input =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]
  
# Using sorted and lambda
Output = sorted(Input, key = lambda x:float(x))
  
# Printing output
print(Output)
Output:



[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

 
Method #2 : Using sorted




# Python code to sort list of decimal values
  
# List initialization
Input =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]
  
# Using sorted + key
Output = sorted(Input, key = float)
  
# Printing output
print(Output)
Output:
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

 
Method #3 : Using sort




# Python code to sort list of decimal values
  
# List initialization
Input =  [12.8, .178, 1.8, 782.7, 99.8, 8.7]
  
# Using sort + key
Input.sort(key = float)
  
# Printing output
print(Input)
Output:
[0.178, 1.8, 8.7, 12.8, 99.8, 782.7]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :