Python | Ways to format elements of given list

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

 
Method #2 : Using Map

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



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

 
Method #3 : Using format

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

 
Method #4 : Using Iteration

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


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.