Python | Ways to sort list of float values

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:



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

 
Method #2 : Using sorted

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

 
Method #3 : Using sort

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.