8. The Basics of Lists#

8.1. Introduction to Lists#

In Python, lists are mutable (Mutable) sequences (Sequence), which means you can change their contents by modifying, adding, or removing elements. Lists are created using square brackets [], and the elements inside are separated by commas. Elements can be of different types (e.g., integers, strings, floats, other lists).

Here’s a breakdown of how lists work in Python:

8.1.1. Creating Lists#

Lists can contain elements of any data type, and they are defined by enclosing the elements in square brackets [].

my_list = ['a', 3.14, 38.86]
print(my_list)  # Output: ['a', 3.14, 38.86]

8.1.2. Accessing Elements#

You can access elements of a list using their index, with indexing starting from 0.

print(my_list[1])  # Output: 3.14

8.1.3. Modifying Elements#

Since lists are mutable, you can change an element at a specific index.

my_list[0] = "zero"
print(my_list)  # Output: ['zero', 3.14, 38.86]

8.1.4. Creating an Empty List#

You can also create an empty list using empty square brackets.

empty_list = []
print(empty_list)  # Output: []

8.2. Common List Methods#

Since the beginning of this course, we have been circling around the concept of objects without fully addressing it. We will once again approach it. Indeed, lists have very interesting functionalities that we will use from now on. However, we will see that these functionalities require a somewhat surprising syntax at first, the dot notation.

Without going into details, objects (see Object), like lists, have methods (see Method). These methods are functions that apply to an object. To call them, you use the name of the variable containing the object, followed by a dot and the method you want to call. This method can, like all functions, have parameters.

Python lists come with a variety of methods that make it easy to manipulate them. Here are some of the most commonly used methods:

8.2.1. Appending Elements#

append(element): Adds an element to the end of the list.

my_list = [3, 4, 3.0]
my_list.append("n")
print(my_list)  # Output: [3, 4, 3.0, 'n']

8.2.2. Inserting Elements#

insert(index, element): Inserts an element at a specified index. All elements from that index onwards are shifted to the right.

my_list = [3, 4, 3.0]
my_list.insert(0, "zero")
print(my_list)  # Output: ['zero', 3, 4, 3.0]

8.2.3. Removing Elements#

pop(index): Removes and returns the element at the specified index. If no index is specified, it removes and returns the last element.

my_list = [3, 4, 3.0]
print(my_list.pop(0))  # Output: 3
print(my_list)  # Output: [4, 3.0]

# Removing the last element
print(my_list.pop())  # Output: 3.0
print(my_list)  # Output: [4]

8.2.4. Sorting Elements#

sort(): Sorts the elements of the list in ascending order. All elements must be comparable. This method sort elements in place. This means that the list is modified.

my_list = [3, 4, 3.0]
my_list.sort()
print(my_list)  # Output: [3, 3.0, 4]
my_list.sort(reverse=True)
print(my_list)  # Output: [4, 3, 3.0]

sorted(): This function is not in place. A new list is created. The original one is not modified.

my_list = [3, 4, 3.0]
second = sorted(my_list)
third = sorted(my_list, reverse=True)
print(my_list) # Output: [3, 4, 3.0]
print(second)  # Output: [3, 3.0, 4]
print(third)  # Output: [4, 3, 3.0]

8.2.5. Reversing Elements#

reverse(): Reverses the order of elements in the list.

my_list = [3, 4, 3.0]
my_list.reverse()
print(my_list)  # Output: [3.0, 4, 3]

8.3. List Comprehensions#

Python offers a highly efficient and expressive syntax for generating lists called list comprehensions (see List Comprehension). This feature allows you to create lists based on a specified pattern by defining how each element is generated. Let’s explore this with an example of creating a list of integers from 1 to 10.

list1 = [i for i in range(1, 11)]
print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In this example, list1 is generated by iterating over each value produced by range(1, 11), and each value is directly added to the list. This method is both concise and readable, providing the same result as the following traditional loop-based approach:

list1 = []
for i in range(1, 11):
    list1.append(i)
print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Instead of adding the values directly, list comprehensions can also include expressions to perform calculations on the elements. For instance, to create a list of squares of integers from 1 to 10, you can use:

list1 = [i for i in range(1, 11)]
list2 = [i * i for i in list1]  # Squares each element in list1
print(list2)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The above list comprehension [i * i for i in list1] computes the square of each integer in list1. This approach can be contrasted with the traditional for-loop version:

list1 = [i for i in range(1, 11)]
list2 = []  # An empty list to store results
for i in list1:
    list2.append(i * i)
print(list2)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

List comprehensions also support filtering elements based on a condition. For example, to generate a list of squares of only the odd numbers from 1 to 10:

list1 = [i for i in range(1, 11)]
list3 = [i * i for i in list1 if i % 2 == 1]  # Includes only odd values
print(list3)

Output:

[1, 9, 25, 49, 81]

8.4. Lists of Lists#

Python does not have a built-in matrix type, but you can represent matrices using lists of lists. In this structure, each element of the main list is itself a list representing a row of the matrix. You can access matrix elements using two sets of square brackets: the first pair to select a row and the second pair to select an element within that row.

matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix)
print(matrix[1][0])  # Accesses the element in the second row, first column

Output:

[[1, 2], [3, 4], [5, 6]]
3

Additionally, matrices can be generated using list comprehensions. For example, to create a 3x3 matrix where each row contains sequential integers from 0 to 2:

matrix = [[i for i in range(3)] for j in range(3)]
print(matrix)

Output:

[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

In this comprehension, [[i for i in range(3)] for j in range(3)], the inner comprehension [i for i in range(3)] creates a row, and the outer comprehension repeats this row three times to form the matrix.