Adding to Lists

Adding to a list

Adding an element to a list is a simple task and can be performed in various ways by incorporating Python methods. Python also offers numerous other methods and functions to use with lists in order to make handling data significantly easier.

The append() method

The append() method adds a single element at the end of a list. This modifies the list in-place.

Consider a list, my_list, containing the values 12, 19, 26, and 23. To add a single value, say 30, we can pass 30 to the append method.

my_list = [12, 19, 26, 23]
my_list.append(30)
print(my_list)

Note: In-place modification means that the same list is modified; it does not create a copy of the original.

The extend() method

The extend() method goes a step further and allows for the addition of multiple elements from another iterable in a list. These elements are appended to the end of the list, also in-place.

Consider a list named python_datatypes, containing a single element, “lists”. To add “tuples” and “sets” in python_datatypes, we can pass the two string literals in the extend() method.

python_datatypes = ["lists"]
python_datatypes.extend(["tuples", "sets"])
print(python_datatypes)

In this case, extend() is immensely useful for combining two lists or adding more than values all at once.