Borislav Hadzhiev
Tue Jun 21 2022·2 min read
Photo by Josh Post
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.
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.
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:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range 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.
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.
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:
Name | Description |
---|---|
index | The index of the element before which to insert |
item | The item to be inserted at the given index |
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.
# 👇️ [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.
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.