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.
primes = [2, 3, 5, 7]
# Append additional prime number, saving returned result
should_be_none = primes.append(11)
# Show that the prime was added
assert primes == [2, 3, 5, 7, 11]
# Show that `None` was returned
assert should_be_none is None
PythonAdd 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:
# List containing single prime number
primes = [2]
# Add an element to the end of the list
primes.append(3)
# Show that the element was added
assert primes == [2, 3]
PythonBe 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:
# List with two prime numbers
primes = [2, 3]
# Try to append multiple numbers at once
primes.append([5, 7])
# Accidentally created a nested list
assert primes == [2, 3, [5, 7]]
PythonOur 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:
# List containing single prime number
primes = [2]
# Extend list by two elements
primes.extend([3, 5])
# Show that both element were added
assert primes == [2, 3, 5]
PythonCaution should be exercised with extend()
because it expects an iterable as an argument and unpacks its elements, resulting in unexpected behavior:
# List of friends
friends = ['Mary', 'Jim']
# Try to extend by additional friend
friends.extend('Jack')
# String is unpacked into individual letters
assert friends == ['Mary', 'Jim', 'J', 'a', 'c', 'k']
PythonTo 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:
# List of friends
friends = ['Mary', 'Jim']
# Extend by additional friend inside list
friends.extend(['Jack'])
# Show that it worked
assert friends == ['Mary', 'Jim', 'Jack']
PythonUse 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:
# List of friends
friends = ['Mary', 'Jim', 'Jack']
# Insert additional friend `“Molly”` before index `2`
friends.insert(2, 'Molly')
# Show that “Molly” was added
assert friends == ['Mary', 'Jim', 'Molly', 'Jack']
PythonBeware of adding multiple elements with insert()
as it can unintentionally create a nested list:
# List of friends
friends = ['Mary', 'Jim']
# Try to insert multiple friends at once
friends.insert(1, ['Molly', 'Lucy'])
# Accidentally created a nested list
assert friends == ['Mary', ['Molly', 'Lucy'], 'Jim']
PythonTo 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:
# List of friends
friends = ['Mary', 'Jim']
# Using `reversed()` keeps order of inserted elements
for friend in reversed(['Molly', 'Lucy']):
friends.insert(1, friend)
# Show that it worked
assert friends == ['Mary', 'Molly', 'Lucy', 'Jim']
PythonUsing 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:
# List of guys
guys = ['Jim', 'Jack']
# List of gals
gals = ['Molly', 'Mary']
# Concatenate both lists
folks = guys + gals
# Show that it worked
assert folks == ['Jim', 'Jack', 'Molly', 'Mary']
PythonUnder the hood the concatenation operator calls the __add__()
method. So the expressions guys + gals
and guys.__add__(gals)
are equivalent:
# Show that both expressions return the same result
assert guys + gals == guys.__add__(gals)
PythonIf 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”:
# Shopping list
groceries = ['Milk', 'Bread', 'Eggs']
# Add butter
groceries += ['Butter']
# Show that it worked
assert groceries == ['Milk', 'Bread', 'Eggs', 'Butter']
PythonThe +=
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:
# List of cities
cities = ['London', 'Paris']
# Attempt to add city; likely not what you intended
cities += 'Rome'
# String is unpacked into individual letters
assert cities = ['London', 'Paris', 'R', 'o', 'm', 'e']
PythonUsing a one-element list appropriately achieves the desired effect of adding another city to the list:
# List of cities
cities = ['London', 'Paris']
# Create a single-element list
cities += ['Rome']
# Now the entire string is added
assert cities = ['London', 'Paris', 'Rome']
PythonUsing 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:
# The `slice()` function constructs a new `slice` object
slice(start, stop, step=1)
PythonFurthermore, there’s a “shorthand” notation for creating slice objects in conjunction with the index operator []
.:
# Select items of list
lst[start:stop:step]
PythonA slice object can be used instead of a numeric index to select multiple elements of a sequence:
people = ['Jim', 'John', 'Mary', 'Jack']
# Select elements between index `1` (inclusive) and `3` (exclusive)
assert people[1:3] == ['John', 'Mary']
# Select every other element
assert people[::2] == ['Jim', 'Mary']
PythonIn 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:
# List of groceries
groceries = ['Milk', 'Bread', 'Eggs']
# Overwrite element at index `1`
groceries[1] = 'Fruit'
# Show that it worked
assert groceries == ['Milk', 'Fruit', 'Eggs']
PythonTo 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:
# List of groceries
groceries = ['Milk', 'Bread', 'Eggs']
# Insert element before index `1`
groceries[1:1] = ['Fruit']
# Show that it worked
assert groceries == ['Milk', 'Fruit', 'Bread', 'Eggs']
PythonUsing this trick you could even insert several elements at once into a Python list which is something the insert()
method cannot do:
# List of groceries
groceries = ['Milk', 'Bread', 'Eggs']
# Insert elements before index `1`
groceries[1:1] = ['Fruit', 'Butter']
# Show that it worked
assert groceries == ['Milk', 'Fruit', 'Butter', 'Bread', 'Eggs']
PythonFurthermore, 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:
# Empty list to be filled
squares = []
# Successively create numbers 0..9
for n in range(10):
# Compute squared number
squared = n * n
# Append squared number to list
squares.append(squared)
# Show that it worked
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
PythonHowever, 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:
# Create first ten square numbers
squares = [n ** 2 for n in range(10)]
# Show that it worked
assert squares == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
PythonAs 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.