How to Add a Float to a List in Python
Python is a very flexible language and allows you to add just about any type of data to a list, regardless of the data type of any of the other elements in the list. One common data type to add to a list is the float data type.
Append
In order to add a float to a list, we can simply use the append()
method:
>>> float_list = [1.0, 2.5, 3.9]
>>> float_list.append(11.2)
>>> float_list
[1.0, 2.5, 3.9, 11.2]
Extend
If you have more than one float to add to your list, or if you have an existing list of floats, you can use the extend()
method:
>>> float_list = [1.0, 2.5, 3.9]
>>> float_list.extend([11.2, 12.3, 13.4])
>>> float_list
[1.0, 2.5, 3.9, 11.2, 12.3, 13.4]
The extend()
method is different from append()
in that it takes an iterable of values, like a list, and adds them to the end of the target list. In essence, this is an easy way to combine two lists together.
Insert
The insert()
method allows you to insert a value into a list at a specific index. For example, the following code inserts the value 11.2
at index 3
:
>>> float_list = [1.0, 2.5, 3.9]
>>> float_list.insert(3, 11.2)
>>> float_list
[1.0, 2.5, 3.9, 11.2]
Obviously this is more useful than the previous two methods if you need to add the float value to a specific spot in the list, as opposed to the end of the list.