Lists are fun­da­men­tal data struc­tures in computer science. Many al­go­rithms 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 struc­tures. We can add elements to a Python list, remove elements, and change their order. There are several ap­proach­es to this, each with its own ad­van­tages and dis­ad­van­tages.

Here are four ap­proach­es that you can use to add elements to a list in Python:

  1. Add elements to a list using Python list methods.
  2. Add elements to a list using list con­cate­na­tion in Python
  3. Add elements to a list using slice notation in Python
  4. Add elements to a list using List Com­pre­hen­sion in Python

Using Python list methods to add elements to a list

In Python, the class list serves as the basis for all list op­er­a­tions. 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 Ex­pla­na­tion
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 mod­i­fi­ca­tion 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.

# List of prime numbers
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
Python

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 il­lus­trate 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]
Python

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:

# 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]]
Python

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 usingex­tend()

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]
Python

Caution should be exercised with extend() because it expects an iterable as an argument and unpacks its elements, resulting in un­ex­pect­ed 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']
Python

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:

# List of friends
friends = ['Mary', 'Jim']
# Extend by additional friend inside list
friends.extend(['Jack'])
# Show that it worked
assert friends == ['Mary', 'Jim', 'Jack']
Python

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:

# 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']
Python

Beware of adding multiple elements with insert() as it can un­in­ten­tion­al­ly 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']
Python

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:

# 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']
Python

Using list con­cate­na­tion in Python to add elements to a list

Another way to add elements to a Python list is through list con­cate­na­tion, using the + operator. This approach is similar to using extend(), but instead of modifying the list in-place, con­cate­na­tion 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']
Python

Under the hood the con­cate­na­tion operator calls the __add__() method. So the ex­pres­sions guys + gals and guys.__add__(gals) are equiv­a­lent:

# Show that both expressions return the same result
assert guys + gals == guys.__add__(gals)
Python

If you’re familiar with Python operators, you might have already guessed that list con­cate­na­tion also supports augmented as­sign­ment. 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']
Python

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 equiv­a­lent in terms of outcome:

  • groceries = groceries + ['Butter']
  • groceries += ['Butter']
  • groceries.__iadd__(['Butter'])
  • groceries.extend(['Butter'])

Caution should be exercised when using list con­cate­na­tion 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']
Python

Using a one-element list ap­pro­pri­ate­ly 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']
Python

Using slice notation to add elements to a list in Python

Slices are a Python feature for selecting con­sec­u­tive elements of a list. The syntax of slices cor­re­sponds to the well-known range() function:

# The `slice()` function constructs a new `slice` object
slice(start, stop, step=1)
Python

Fur­ther­more, there’s a “shorthand” notation for creating slice objects in con­junc­tion with the index operator [].:

# Select items of list
lst[start:stop:step]
Python

A 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']
Python

In com­bi­na­tion with as­sign­ments slices can be used as an al­ter­na­tive for list methods such as append(), extend() and insert():

list method Cor­re­spond­ing slice as­sign­ment Ex­pla­na­tion
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 un­der­stand 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']
Python

To insert an element using index as­sign­ment, 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 as­sign­ment 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']
Python

Using 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']
Python

Fur­ther­more, slice as­sign­ments can be used to se­lec­tive­ly overwrite elements of a list. All in all, slices are a very flexible feature that should be part of every Python pro­gram­mer’s toolbox.

Add Python elements to a list with List Com­pre­hen­sion

A common scenario in Python is pop­u­lat­ing a new list with elements. The standard approach, which is ap­plic­a­ble in Python as well as most pro­gram­ming languages, works as follows:

  1. Create empty list
  2. Create elements by loop
  3. Extend list by created element

To exemplify, let’s look at gen­er­at­ing 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]
Python

However, Python offers a more efficient approach known as List Com­pre­hen­sion for gen­er­at­ing 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]
Python

As elegant as they are, List Com­pre­hen­sions are only suitable for filling a new list. To extend an existing list, you can use the methods we’ve already discussed.

Tip

To deploy websites and apps via GitHub more easily, you can use Deploy Now from IONOS.

Go to Main Menu