Skip to content
Related Articles

Related Articles

Improve Article

Python | Ways to format elements of given list

  • Last Updated : 01 Mar, 2019

Given a List of float values, the task is to truncate all float values to 2-decimal digit. Let’s see the different methods to do the task.

Method #1 : Using List comprehension




# Python code to truncate float
# values to 2-decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using list comprehension
Output = ["%.2f" % elem for elem in Input]
  
# Printing output
print(Output)
Output:
['100.77', '17.23', '60.99', '300.84']

 
Method #2 : Using Map




# Python code to truncate float 
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using map
Output = map(lambda n: "%.2f" % n, Input)
  
# Converting to list
Output = list(Output)
  
# Print output
print(Output)
Output:



['100.77', '17.23', '60.99', '300.84']

 
Method #3 : Using format




# Python code to truncate float
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using forrmat
Output = ['{:.2f}'.format(elem) for elem in Input]
  
# Print output
print(Output)
Output:
['100.77', '17.23', '60.99', '300.84']

 
Method #4 : Using Iteration




# Python code to truncate float
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Output list initialization
Output = []
  
# Iterating
for elem in Input:
    Output.append("%.2f" % elem)
  
# Printing output
print(Output)
Output:
['100.77', '17.23', '60.99', '300.84']

 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 :