Round all numbers in a list in Python

Last updated: Jul 12, 2022

Photo from Unsplash

Round all numbers in a list in Python#

To round all numbers in a list:

1. Use a list comprehension to iterate over the list.
2. On each iteration, pass the list element to the `round()` function.
3. The new list will contain rounded numbers.
main.py
```Copied!```my_list = [2.340000001, 3.4500001, 4.5600006]

# ✅ round numbers in list to 2 digits

new_list = [round(item, 2) for item in my_list]
print(new_list)  # 👉️ [2.34, 3.45, 4.56]

# ----------------------------------------------

# ✅ round numbers in list to nearest integer

new_list = [round(item) for item in my_list]
print(new_list)  # 👉️ [2, 3, 5]
``````

We used a list comprehension to iterate over the list.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we pass the current list element to the `round()` function.

The round function takes the following 2 parameters:

NameDescription
`number`the number to round to `ndigits` precision after the decimal
`ndigits`the number of digits after the decimal, the number should have after the operation (optional)
The `round` function returns the number rounded to `ndigits` precision after the decimal point.

If `ndigits` is omitted, the function returns the nearest integer.

main.py
```Copied!```my_list = [2.340000001, 3.4500001, 4.5600006]

new_list = [round(item, 2) for item in my_list]
print(new_list)  # 👉️ [2.34, 3.45, 4.56]

# ----------------------------------------------

new_list = [round(item) for item in my_list]
print(new_list)  # 👉️ [2, 3, 5]
``````

Alternatively, you can use the `numpy` module.

Round all numbers in a list using Numpy#

To round all numbers in a list:

1. Use the `numpy.array()` method to convert the list to a numpy array.
2. Pass the array and the number of digits to round to to the `numpy.around()` method.
3. Use the `list()` class to convert the array to a list.
main.py
```Copied!```import numpy as np

my_list = [2.340000001, 3.4500001, 4.5600006]

new_list = list(np.around(np.array(my_list), 2))

print(new_list)  # 👉️ [2.34, 3.45, 4.56]
``````

The numpy.array method takes an object and creates an array from the given object.

The numpy.around method takes an array and the number of decimal places to round to and evenly rounds all elements in the array to the given number of decimals.

The `decimals` argument is `0` by default.

The last step is to use the `list()` class to convert the numpy array to a list.

The list class takes an iterable and returns a list object.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
You can use the search field on my Home Page to filter through all of my articles.