Believemy logo purple

Lists in Python

In Python, a list is a variable used to store several elements.
Believemy logo

In Python, lists are one of the most fundamental and versatile data types. They allow you to store ordered sequences of values that can be easily traversed, modified, sorted, filtered, etc.

A list is therefore an ordered, modifiable, and indexable collection.

Unlike a tuple, a list can be modified after its creation.

 

What is a list in Python?

A list is a sequence of ordered values (each element has a position) and mutable (you can modify existing elements, add or remove them).

PYTHON
fruits = ["apple", "banana", "kiwi"]

In this example:

  • "apple" is at index 0;
  • "banana" is at index 1;
  • "kiwi" is at index 2.

Indexes in Python start at 0, not 1. 😉

 

Creating a list

To create a list, simply use a pair of brackets: [].

PYTHON
numbers = [1, 2, 3, 4]

It's also possible to create a list from another type (cast).

PYTHON
text = "hello"
letters = list(text)  # ['h', 'e', 'l', 'l', 'o']

Although this may seem quite strange, it's something we use very often with loops!

 

Accessing list elements

To access list elements, we use indices:

PYTHON
fruits = ["apple", "banana", "kiwi"]
print(fruits[0])  # apple
print(fruits[-1])  # kiwi (negative index: from the end)

When we try to access an index that doesn't exist, an error is raised.

PYTHON
print(fruits[3])  # ❌ IndexError: the list only has 3 elements (0 to 2)

 

Modifying a list

Lists in Python are mutable, which means you can modify their elements directly.

PYTHON
colors = ["red", "blue", "green"]
colors[1] = "yellow"
print(colors)  # ['red', 'yellow', 'green']

This flexibility is a great advantage of lists, but it requires being careful when sharing or copying.

 

Adding or inserting elements

Python offers three methods to enrich a list:

  1. append() - add an element at the end;
  2. insert() - add an element at a specific position;
  3. extend() - add multiple elements.

Method #1 - append()

PYTHON
numbers = [1, 2, 3]
numbers.append(4)
# [1, 2, 3, 4]

 

Method #2 - insert()

PYTHON
numbers = [1, 2, 3]
numbers.insert(1, 10)  # Insert 10 at index 1
# [1, 10, 2, 3]

 

Method #3 - extend()

This method is also used to merge lists.

PYTHON
numbers = [1, 2, 3]
numbers.extend([5, 6])
# [1, 2, 3, 5, 6]

 

Removing elements from a list

Just like adding elements to a list, there are three different methods to remove elements:

  1. del - removes an element by its index;
  2. remove() - removes the first occurrence of a value;
  3. pop() - removes and returns the last one.

Method #1 - del

PYTHON
del numbers[1]

 

Method #2 - remove()

PYTHON
numbers.remove(3)

 

Method #3 - pop()

PYTHON
last = numbers.pop()  # Remove and return the last

 

Clearing a list

It's possible to clear a list with the clear() method:

PYTHON
numbers.clear()

 

Iterating through a list

The simplest method to iterate through a list is the for loop:

PYTHON
animals = ["cat", "dog", "rabbit"]
for animal in animals:
    print(animal)

It's also possible to access the index and value of a list element using enumerate():

PYTHON
for i, animal in enumerate(animals):
    print(f"{i}{animal}")

 

List comprehensions

A list comprehension is a concise and elegant way to create a new list from another, often combined with a transformation or condition. It's similar to a dictionary comprehension.

They are often faster and more readable than classic loops for simple transformations.

 

Syntax

PYTHON
[new_element for element in iterable]

 

Examples

Double each number

PYTHON
numbers = [1, 2, 3]
doubles = [x * 2 for x in numbers]

 

Keep only even numbers

PYTHON
evens = [x for x in numbers if x % 2 == 0]

 

Searching in a list

Testing if a value is present

We can search if a value is present in a Python list using the in keyword.

PYTHON
"cat" in animals  # True
"tiger" in animals  # False

 

Finding the index of an element

PYTHON
index = animals.index("dog")  # 1

This method is special: it raises an error (ValueError) when the element doesn't exist.

 

Counting occurrences

To count occurrences in a list, simply use the count() method.

PYTHON
animals.count("cat")  # 1

 

Sorting and reversing a list

Sorting a list

Sorting a list allows you to reorganize its elements according to a specific order: ascending, descending, or according to a custom key (length, alphabetical order, etc.).

There are two main ways to sort a list:

  1. by modifying the original (with sort());
  2. or by returning a new sorted list (with sorted()).

Sorting by modifying the original list with sort()

PYTHON
grades = [15, 10, 20]
grades.sort()
print(grades)  # [10, 15, 20]

This method modifies the original list directly. If you need to keep the original list intact, avoid sort().

 

Sorting without modifying the original list with sorted()

PYTHON
grades = [15, 10, 20]
new_grades = sorted(grades)

Here, sorted() creates a new sorted list without touching the original list.

It's also possible to specify reverse=True for reverse sorting:

PYTHON
grades = [15, 10, 20]
new_grades = sorted(grades, reverse=True)

Finally, sorted() accepts a key parameter to sort according to a custom rule, like string length or a lambda function.

 

Reversing a list

PYTHON
grades = [15, 10, 20]
grades.reverse()

Unlike sorting, this method doesn't organize the values. It simply reverses the order of elements in the current list, without creating a copy. 🥸

 

Copying a list

Since lists are mutable, it's essential to master copying.

Copying a list shouldn't simply copy the reference, but actually duplicate its content to avoid side effects.

To do this, we have two methods:

  1. Slicing with the [:] operator;
  2. And a dedicated method with copy().

Method #1: slicing ([:])

PYTHON
copy = grades[:]

This method creates a shallow copy of the list: elements are duplicated, but nested objects remain linked (modifying the copy also modifies the original list).

 

Method #2: copy()

PYTHON
copy = grades.copy()

Works like slicing, but more explicitly. It's also recommended for its readability. 😊

Both methods above don't work for lists of lists:

PYTHON
list = [[1], [2]]
copy = list.copy()
copy[0][0] = 99
print(list)  # [[99], [2]]

As we can see, modifying a sub-element also modifies the original. Why? Because only the reference to the sub-list is copied. 😉

It's therefore better to favor a deep copy with copy.deepcopy():

PYTHON
import copy
full_copy = copy.deepcopy(list)

This method recursively copies the entire structure, guaranteeing total independence.

 

Useful methods for lists

Python provides a rich palette of methods to add, remove, sort, count or search elements in a list.

Here's a small summary table that every Python developer should keep in mind:

MethodDescription
append(x)Add an element at the end
insert(i, x)Insert an element x at index i
extend(list)Add multiple elements / merge another list
remove(x)Remove the first occurrence of x
pop()Remove and return the last element
clear()Empty the list
index(x)Give the index of the first occurrence of x
count(x)Count the number of occurrences of x
sort()Sort the list

 

Nested lists

A nested list (or list of lists) is a structure where each element can itself be a list.

This allows you to represent multidimensional arrays or complex structures, like matrices or data tables.

Here's a small example:

PYTHON
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

Finally, to access a specific element:

PYTHON
print(matrix[1][2])  # 6

Each index accesses a level. matrix[1] returns the row [4, 5, 6], and [1][2] targets the 3rd value of that row.

Nested lists are very powerful but can quickly become difficult to read. Think about formatting them well and using nested loops to traverse them properly. 😬

 

Frequently asked questions about lists

Let's review the most frequently asked questions when talking about lists in Python.

What does list() do exactly?

It converts any iterable to a list: strings, tuples, range(), etc.

PYTHON
list("abc")  # ['a', 'b', 'c']

 

Can you sort a list of strings?

Yes, strings are sorted in alphabetical order with the sort() method we saw.

 

Can I learn Python on my own?

Of course, good Python training is possible! Discover our course here.

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.