# 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](https://www.ionos.com/digitalguide/websites/web-development/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:

1. Add elements to a list using Python `list` methods.
2. Add elements to a list using list concatenation in Python
3. Add elements to a list using slice notation in Python
4. 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:

<table>
  <thead>
    <tr>
      <th>`list` method</th>
      <th>Arguments</th>
      <th>Explanation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`append()`</td>
      <td>`element`</td>
      <td>Add a single element to the end of the list</td>
    </tr>
    <tr>
      <td>`extend()`</td>
      <td>`[elements]`</td>
      <td>Add multiple elements to the end of the list</td>
    </tr>
    <tr>
      <td>`insert()`</td>
      <td>`index, element`</td>
      <td>Add a single element before the given index</td>
    </tr>
  </tbody>
</table>

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.

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

### Add a single element to the end of the list using append()

You can use [Python-`append()`](https://www.ionos.com/digitalguide/websites/web-development/python-append/) to add a **single element to the end of an existing list**. Let’s illustrate this using an example:

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

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:

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

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()`](https://www.ionos.com/digitalguide/websites/web-development/python-extend/) works similarly to `append()`, except that **several elements are added to an existing list**. Let’s look at an example:

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

Caution should be exercised with `extend()` because it expects an **iterable as an argument and unpacks its elements**, resulting in unexpected behavior:

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

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:

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

### 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()`](https://www.ionos.com/digitalguide/websites/web-development/python-insert/) which takes a numeric index in addition to the element to be inserted:

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

Beware of adding multiple elements with `insert()` as it can unintentionally **create a nested list**:

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

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:

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

## 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:

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

Under the hood **the concatenation operator calls the `__add__()` method**. So the expressions `guys + gals` and `guys.__add__(gals)` are equivalent:

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

If you’re familiar with [Python operators](https://www.ionos.com/digitalguide/websites/web-development/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”:

```Python
# Shopping list
groceries = ['Milk', 'Bread', 'Eggs']
# Add butter
groceries += ['Butter']
# Show that it worked
assert groceries == ['Milk', 'Bread', 'Eggs', 'Butter']
```

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:

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

Using a **one-element list appropriately achieves the desired effect** of adding another city to the list:

```Python
# List of cities
cities = ['London', 'Paris']
# Create a single-element list
cities += ['Rome']
# Now the entire string is added
assert cities = ['London', 'Paris', 'Rome']
```

## 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:

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

Furthermore, there’s a **“shorthand” notation for creating slice objects** in conjunction with the index operator `[]`.:

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

A **slice object can be used instead of a numeric index** to select multiple elements of a sequence:

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

In **combination with assignments** slices can be used as an alternative for `list` methods such as `append()`, `extend()` and `insert()`:

<table>
  <thead>
    <tr>
      <th>`list` method</th>
      <th>Corresponding slice assignment</th>
      <th>Explanation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>`lst.append(element)`</td>
      <td>`lst[len(lst)+1:] = [element]`</td>
      <td>Add an item to the end of the list</td>
    </tr>
    <tr>
      <td>`lst.extend([elements])`</td>
      <td>`lst[len(lst)+1:] = [elements]`</td>
      <td>Add multiple elements to the end of the list</td>
    </tr>
    <tr>
      <td>`lst.insert(index, element)`</td>
      <td>`lst[index:index] = [element]`</td>
      <td>Add an element before the given index</td>
    </tr>
  </tbody>
</table>

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:

```Python
# List of groceries
groceries = ['Milk', 'Bread', 'Eggs']
# Overwrite element at index `1`
groceries[1] = 'Fruit'
# Show that it worked
assert groceries == ['Milk', 'Fruit', 'Eggs']
```

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:

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

Using this trick you could even **insert several elements at once** into a Python list which is something the `insert()` method cannot do:

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

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:

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

To exemplify, let’s look at **generating the list of the first ten square numbers**:

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

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:

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

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.

Tip To deploy websites and apps via GitHub more easily, you can use [Deploy Now](https://www.ionos.com/hosting/deploy-now "Deploy Now - Deploy Websites and Apps via GitHub - IONOS") from IONOS.


This is a markdown version of: [https://www.ionos.com/digitalguide/websites/web-development/python-add-to-list/](https://www.ionos.com/digitalguide/websites/web-development/python-add-to-list/) for AI/LLM consumption.