Convert a list of integers to a list of floats in Python

avatar

Borislav Hadzhiev

Last updated: Jul 12, 2022

banner

Photo from Unsplash

Convert a list of integers to a list of floats in Python #

To convert a list of integers to a list of floats:

  1. Use a list comprehension to iterate over the list.
  2. Use the float() class to convert each integer to a float.
  3. The new list will only contain floating-point numbers.
main.py
list_of_integers = [3, 5, 7, 9] new_list = [float(item) for item in list_of_integers] # 👇️ [3.0, 5.0, 7.0, 9.0] print(new_list)

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

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 integer to the float() class to convert it to a floating-point number.

The new list will only contain float values.

Alternatively, you can use the map() function.

Convert a list of integers to a list of floats using map() #

To convert a list of integers to a list of floats:

  1. Pass the float() class and the list to the map() function.
  2. The map() function will call the float() class with each item in the list.
  3. Use the list() class to convert the map object to a list.
main.py
list_of_integers = [3, 5, 7, 9] new_list = list(map(float, list_of_integers)) # 👇️ [3.0, 5.0, 7.0, 9.0] 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 float() class gets passed each integer in the list and converts each value to a floating-point number.

Lastly, we used the list() class to convert the map object to a list.

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

Convert a list of integers to a list of floats using numpy #

To convert a list of integers to a list of floats:

  1. Pass the list and the float data type to the numpy.array() method.
  2. Optionally convert the numpy array to a list.
main.py
import numpy as np list_of_integers = [3, 5, 7, 9] new_list = list( np.array(list_of_integers, dtype=np.float32) ) # 👇️ [3.0, 5.0, 7.0, 9.0] print(new_list)

The numpy.array method creates an array from the provided object.

We set the dtype argument to np.float32 to specify the desired data type for the elements in the array.

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

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 using a list comprehension because I find it the most direct and the easiest to read out of the options.

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.