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

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]

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :