Python - Ways to format elements of given list

PythonServer Side ProgrammingProgramming

A list is a collection which is ordered and changeable. In Python lists are written with square brackets. You access the list items by referring to the index number. Negative indexing means beginning from the end, -1 refers to the last item. You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.

Example

 Live Demo

# 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)
# 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)
# 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)
# 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']
['100.77', '17.23', '60.99', '300.84']
['100.77', '17.23', '60.99', '300.84']
['100.77', '17.23', '60.99', '300.84']
raja
Published on 06-Aug-2020 14:05:37
Advertisements