Last modified: Oct 28, 2024 By Alexander Williams
Python Print List of Numbers with Precision
When working with lists of floating-point numbers, you may want to format each number to a specific precision, especially for readability or presentation purposes.
Using round()
to Set Precision for Each Element
The round()
function allows us to specify the decimal precision of each number in the list. This is effective for rounding each item individually.
# Rounding each element in a list to 2 decimal places
numbers = [3.14159, 2.71828, 1.61803]
rounded_numbers = [round(num, 2) for num in numbers]
print(rounded_numbers)
Output:
[3.14, 2.72, 1.62]
Using String Formatting for Precision in Output
For more control over how numbers appear, use Python's f-strings for in-place formatting during printing.
# Using f-strings to print with precision
numbers = [3.14159, 2.71828, 1.61803]
formatted_numbers = [f"{num:.2f}" for num in numbers]
print(formatted_numbers)
Each number in formatted_numbers
will be a string formatted to two decimal places.
Output:
['3.14', '2.72', '1.62']
Using format()
Method for List Precision
The format()
method can also be used to format each number individually, offering flexibility in how numbers are presented.
# Using format() for precision
numbers = [3.14159, 2.71828, 1.61803]
formatted_numbers = ["{:.2f}".format(num) for num in numbers]
print(formatted_numbers)
This produces a list of strings, each with a specified precision.
Output:
['3.14', '2.72', '1.62']
Combining Precision with join()
for Printing
When you need to print all numbers as a single line, combine join()
with formatting. This approach is useful for displaying lists compactly.
# Joining numbers with precision in a single line
numbers = [3.14159, 2.71828, 1.61803]
formatted_numbers = ", ".join(f"{num:.2f}" for num in numbers)
print(formatted_numbers)
Output:
3.14, 2.72, 1.62
Printing Lists with Precision Using map()
map()
can simplify formatting by applying format()
to each list item, and it works well with join()
for compact display.
# Using map to format and print numbers with precision
numbers = [3.14159, 2.71828, 1.61803]
formatted_numbers = ", ".join(map(lambda x: f"{x:.2f}", numbers))
print(formatted_numbers)
Output:
3.14, 2.72, 1.62
Conclusion
Python offers multiple ways to format lists of numbers with precision. Choose a method based on your specific needs and output requirements.
For more details, see the official Python documentation on rounding.