How to add a float to a list in Python

avatar

Borislav Hadzhiev

Tue Jun 21 20222 min read

banner

Photo by Josh Post

Add a float to a list in Python #

Use the list.append() method to add a float to a list in Python, e.g. my_list.append(3.3). The list.append() method adds an item to the end of the list.

main.py
my_list = [1.1, 2.2] my_list.append(3.3) print(my_list) # 👉️ [1.1, 2.2, 3.3] my_list.extend([4.4, 5.5]) print(my_list) # 👉️ [1.1, 2.2, 3.3, 4.4, 5.5] my_list.insert(0, 9.9) print(my_list) # 👉️ [9.9, 1.1, 2.2, 3.3, 4.4, 5.5]

The first example uses the list.append method to add a float to the end of the list.

If you need to add a range of floating-point numbers to a list, use the range() class.

main.py
my_list = [] for i in range(1, 5): my_list.append(i + 0.1) print(my_list) # 👉️ [1.1, 2.1, 3.1, 4.1]

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

If you need to add multiple floating-point numbers to a list, use the list.extend() method.

main.py
my_list = [1.1, 2.2] my_list.extend([3.3, 4.4]) print(my_list) # 👉️ [1.1, 2.2, 3.3, 4.4]

The list.extend method takes an iterable (such as a list) and extends the list by appending all of the items from the iterable.

If you need to add a float at a specific position in a list, use the insert() method.

main.py
my_list = [1.1, 2.2] my_list.insert(0, 9.9) print(my_list) # 👉️ [9.9, 1.1, 2.2]

Indexes are zero-based in Python. In other words, the first item in the list has an index of 0.

The list.insert method inserts an item at a given position.

The method takes the following 2 parameters:

NameDescription
indexThe index of the element before which to insert
itemThe item to be inserted at the given index
You can also wrap the floating-point numbers you want to add to the list in square brackets to make them items of another list and use the addition (+) operator to combine the two lists.
main.py
my_list = [1.1, 2.2] float_1 = 3.3 float_2 = 4.4 new_list = my_list + [float_1, float_2] print(new_list) # 👉️ [1.1, 2.2, 3.3, 4.4]

When the addition (+) operator is used with 2 lists, we get a new list that contains the items from the two lists.

main.py
# 👇️ [1.1, 2.2, 3.3, 4.4] print([1.1, 2.2] + [3.3, 4.4])

Alternatively, you can use an asterisk * to unpack the list items into a new list that contains the floating-point numbers you want to add.

main.py
my_list = [1.1, 2.2] float_1 = 3.3 float_2 = 4.4 new_list = [*my_list, float_1, float_2] print(new_list) # 👉️ [1.1, 2.2, 3.3, 4.4]

The asterisk * unpacks the items of the list into the new list.

Use the search field on my Home Page to filter through my more than 1,000 articles.