We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

20
509.403,30

Cart

Quantity 18,00

Convert a List of floats to List of integers in Python

This tutorial will discuss about unique ways to convert a list of floats to list of integers in Python.

Table Of Contents

Method 1: Using List Comprehension and int()

Iterate over all elements of List using a for loop. During iteration convert each float to integer using the int() method, and construct a new list of these integers using List Comprehension.

Advertisements

Let’s see the complete example,

listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8]

# convert list of floats to list of integers
listOfInts = [int(elem) for elem in listOfFloats]

print(listOfInts)

Output

[11, 12, 13, 15, 18, 29]

It connverted a List of floats into a list of integers.

Important Point: int() method will convert the float to int, but it will not round off the value, it will just remove the decimal part. For example, 13.7 will be converted to 13 only. If you want the float values to round off while converted them to integer like, 13.7 to 14, then you need to use the round() method instead of int(). As we have shown in the next example.

Method 2: Using List Comprehension and round()

Iterate over all elements of List using a for loop. During iteration convert each float to integer using the round() method, and construct a new list of these integers using List Comprehension. The round() will completely round of the value i.e 14.8 will be 15.

Let’s see the complete example,

listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8]

# convert list of floats to list of integers
listOfInts = [round(elem) for elem in listOfFloats]

print(listOfInts)

Output

[11, 12, 14, 16, 18, 30]

Method 3: Using map() function

Pass the round() method, and list of floats to the map() function. It will apply round() method on each float in the list, to round off its value and convert it to integer. It stores all the converted integers in a mapped object. Then convert that mapped object into a list of integers using list() method.

Let’s see the complete example,

listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8]

# convert list of floats to list of integers
listOfInts = list(map(round, listOfFloats))

print(listOfInts)

Output

[11, 12, 14, 16, 18, 30]

Summary

We learned about three ways to convert a list of floats into a list of integers in Python.

20
509.403,30

Cart

Quantity 18,00