- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python - Ways to format elements of given list
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
# 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']
Advertisements