Round a list of floats into integers in Python

avatar

Borislav Hadzhiev

Last updated: Jul 12, 2022

banner

Check out my new book

Round a list of floats into integers in Python #

To round a list of floats into integers:

  1. Use a list comprehension to iterate over the list.
  2. On each iteration, pass the current float to the round() function.
  3. The new list will only contain integer values.
main.py
list_of_floats = [2.4, 3.5, 6.7, 8.1] new_list = [round(item) for item in list_of_floats] # 👇️ [2, 4, 7, 8] print(new_list)

We used a list comprehension to iterate over the list of floats.

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 to round it to the nearest integer.

The round function takes the following 2 parameters:

NameDescription
numberthe number to round to ndigits precision after the decimal
ndigitsthe 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
fav_num = 3.456 result1 = round(fav_num) print(result1) # 👉️ 3 result2 = round(fav_num, 2) print(result2) # 👉️ 3.46

Alternatively, you can use the map() function.

Round a list of floats into integers using map() #

To round a list of floats into integers:

  1. Pass the round() function and the list to the map() function.
  2. The map() function will pass each float to the round() function.
  3. Use the list() class to convert the map object to a list.
main.py
list_of_floats = [2.4, 3.5, 6.7, 8.1] new_list = list(map(round, list_of_floats)) # 👇️ [2, 4, 7, 8] print(new_list)

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function calls the round() function will each floating-point number in the list and rounds each value.

The last step is to use the list() class to convert the map object to a list.

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

Which approach you pick is a matter of personal preference. I'd go with the list comprehension as I find it more direct and easier to read.

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