Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Ways to format elements of given list
When working with lists containing numeric values, you often need to format them for better readability or presentation. Python provides several methods to format list elements, including list comprehension with string formatting, map() function, and modern f-string formatting.
Using List Comprehension with % Formatting
The traditional approach uses list comprehension with percentage formatting ?
numbers = [100.7689454, 17.232999, 60.98867, 300.83748789] # Format to 2 decimal places using % formatting formatted = ["%.2f" % elem for elem in numbers] print(formatted)
['100.77', '17.23', '60.99', '300.84']
Using map() Function
The map() function applies formatting to each element using a lambda function ?
numbers = [100.7689454, 17.232999, 60.98867, 300.83748789] # Using map with lambda function formatted = map(lambda n: "%.2f" % n, numbers) formatted_list = list(formatted) print(formatted_list)
['100.77', '17.23', '60.99', '300.84']
Using .format() Method
The .format() method provides more readable string formatting ?
numbers = [100.7689454, 17.232999, 60.98867, 300.83748789]
# Using .format() method with list comprehension
formatted = ['{:.2f}'.format(elem) for elem in numbers]
print(formatted)
['100.77', '17.23', '60.99', '300.84']
Using f-strings (Python 3.6+)
F-strings provide the most modern and readable approach to string formatting ?
numbers = [100.7689454, 17.232999, 60.98867, 300.83748789]
# Using f-strings for formatting
formatted = [f'{elem:.2f}' for elem in numbers]
print(formatted)
['100.77', '17.23', '60.99', '300.84']
Comparison
| Method | Readability | Performance | Python Version |
|---|---|---|---|
| % formatting | Good | Fast | All versions |
| map() function | Moderate | Fast | All versions |
| .format() method | Very Good | Moderate | 2.7+ |
| f-strings | Excellent | Fastest | 3.6+ |
Conclusion
F-strings offer the best combination of readability and performance for formatting list elements. Use .format() for older Python versions or when you need complex formatting options.
