How to add to a Python list
Lists are fundamental data structures in computer science. Many algorithms rely on modifying lists. Find out how to add elements to a list in Python.
How to add elements to a Python list?
Unlike tuples and strings, lists in Python are “mutable”, that is, mutable data structures. We can add elements to a Python list, remove elements, and change their order. There are several approaches to this, each with its own advantages and disadvantages.
Here are four approaches that you can use to add elements to a list in Python:
- Add elements to a list using Python
list
methods. - Add elements to a list using list concatenation in Python
- Add elements to a list using slice notation in Python
- Add elements to a list using List Comprehension in Python
Using Python list methods to add elements to a list
In Python, the class list
serves as the basis for all list operations. A class defines a set of methods for list objects. These include three methods that are suitable for adding elements to a list:
list method |
Arguments | Explanation |
---|---|---|
append()
|
element
|
Add a single element to the end of the list |
extend()
|
[elements]
|
Add multiple elements to the end of the list |
insert()
|
index, element
|
Add a single element before the given index |
One crucial aspect to note is that the modification performed by the three mentioned methods is done “in-place”. This means that the list object itself is modified instead of creating and returning a new list. As a result, all three methods return None
instead of a modified list.
Add a single element to the end of the list using append()
You can use Python-append()
to add a single element to the end of an existing list. Let’s illustrate this using an example:
Be careful when using append()
– the method always adds a single element. If the element to be added is another list, the result will be a nested list:
Our attempt to create the list [2, 3, 5, 7]
failed. To add multiple elements we better use the extend()
method.
Add elements to the end of the list usingextend()
Python-extend()
works similarly to append()
, except that several elements are added to an existing list. Let’s look at an example:
Caution should be exercised with extend()
because it expects an iterable as an argument and unpacks its elements, resulting in unexpected behavior:
To add a single element to a Python list, either use append()
or enclose the element in a list with square brackets. Then the call to extend()
will work:
Use insert() to add a single element before the specified index
So far we’ve shown how to add one or more elements to the end of a Python list. However, what if we want to insert an element at an arbitrary position? For this case, you can use Python-insert()
which takes a numeric index in addition to the element to be inserted:
Beware of adding multiple elements with insert()
as it can unintentionally create a nested list:
To insert multiple elements within a list, we use a for
loop. We can also use the reversed()
function to keep the order of the inserted elements:
Using list concatenation in Python to add elements to a list
Another way to add elements to a Python list
is through list concatenation, using the +
operator. This approach is similar to using extend()
, but instead of modifying the list in-place, concatenation creates a new list with the added elements.
Let’s create two lists and add the second to the first. Since the operation returns a new list, we assign the return value to a new list:
Under the hood the concatenation operator calls the __add__()
method. So the expressions guys + gals
and guys.__add__(gals)
are equivalent:
If you’re familiar with Python operators, you might have already guessed that list concatenation also supports augmented assignment. The +=
operator is used to add elements to a list “in-place”:
The +=
operator calls the __iadd__()
method, where the “i” stands for “in-place”. Similar to the extend()
method, the object on which the method is called is modified directly. So the following lines are equivalent in terms of outcome:
groceries = groceries + ['Butter']
groceries += ['Butter']
groceries.__iadd__(['Butter'])
groceries.extend(['Butter'])
Caution should be exercised when using list concatenation operators to add a single element to a list. A single element must be contained in a list, otherwise an iterable may be unpacked:
Using a one-element list appropriately achieves the desired effect of adding another city to the list:
Using slice notation to add elements to a list in Python
Slices are a Python feature for selecting consecutive elements of a list. The syntax of slices corresponds to the well-known range()
function:
Furthermore, there’s a “shorthand” notation for creating slice objects in conjunction with the index operator []
.:
A slice object can be used instead of a numeric index to select multiple elements of a sequence:
In combination with assignments slices can be used as an alternative for list
methods such as append()
, extend()
and insert()
:
list method |
Corresponding slice assignment | Explanation |
---|---|---|
lst.append(element)
|
lst[len(lst)+1:] = [element]
|
Add an item to the end of the list |
lst.extend([elements])
|
lst[len(lst)+1:] = [elements]
|
Add multiple elements to the end of the list |
lst.insert(index, element)
|
lst[index:index] = [element]
|
Add an element before the given index |
To understand how this works, let’s examine the process of assigning a list element using a numeric index. This allows us to overwrite a single element within the list:
To insert an element using index assignment, we can utilize a slice that includes the desired index as the start
and stop
values. It’s important to note that for the slice assignment to work correctly, there must be a list on the right side of the equal sign:
Using this trick you could even insert several elements at once into a Python list which is something the insert()
method cannot do:
Furthermore, slice assignments can be used to selectively overwrite elements of a list. All in all, slices are a very flexible feature that should be part of every Python programmer’s toolbox.
Add Python elements to a list with List Comprehension
A common scenario in Python is populating a new list with elements. The standard approach, which is applicable in Python as well as most programming languages, works as follows:
- Create empty list
- Create elements by loop
- Extend list by created element
To exemplify, let’s look at generating the list of the first ten square numbers:
However, Python offers a more efficient approach known as List Comprehension for generating a list without the need for a for
loop or an empty list variable:
As elegant as they are, List Comprehensions are only suitable for filling a new list. To extend an existing list, you can use the methods we’ve already discussed.
To deploy websites and apps via GitHub more easily, you can use Deploy Now from IONOS.