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.
In order to add a float to a list, we can simply use the
1.0, 2.5, 3.9] float_list.append(11.2) float_list [1.0, 2.5, 3.9, 11.2]float_list = [
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
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]float_list = [
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() 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
1.0, 2.5, 3.9] float_list.insert(3, 11.2) float_list [1.0, 2.5, 3.9, 11.2]float_list = [
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.