Skip to content
Related Articles

Related Articles

Python | Ways to format elements of given list

Improve Article
Save Article
  • Last Updated : 15 Oct, 2021
Improve Article
Save Article

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 
 

Python3




# 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 
 

Python3




# 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 
 

Python3




# Python code to truncate float
# values to 2 decimal digits.
 
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
 
# Using format
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 
 

Python3




# 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']

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!