TutreNews Learn

Lists

Lists, indexing and slicing

Goal: Create lists and read parts of them with indexes and slices · 9 min

A list stores an ordered collection of values in square brackets: numbers = [10, 20, 30, 40]. It can mix types ([1, "a", True]) and be empty ([]).

Indexing starts at 0. Negative indexes count from the end:

letters = ["a", "b", "c", "d", "e"]
print(letters[0])    # a   (first)
print(letters[2])    # c
print(letters[-1])   # e   (last)

An index outside the list raises an IndexError. len(letters) gives the number of items (5), so the last valid index is len(letters) - 1.

Slicing takes a part: letters[start:stop] includes start and excludes stop:

print(letters[1:4])   # ['b', 'c', 'd']
print(letters[:2])    # ['a', 'b']   (from the start)
print(letters[3:])    # ['d', 'e']   (to the end)
print(letters[::2])   # ['a', 'c', 'e'] (step 2)
print(letters[::-1])  # ['e', 'd', 'c', 'b', 'a'] (reversed copy)

Slices never raise IndexError and always return a new list. Other basics: x in letters tests membership (True/False), letters + ["f"] joins lists, ["a"] * 3 repeats.

Worked example: Slicing the middle

  1. data = [5, 6, 7, 8, 9]. We want [6, 7, 8].
  2. Index 1 is the 6, and the slice must stop before index 4: data[1:4].
  3. data[-1] gives 9 and data[::-1] gives the reversed list.
data = [5, 6, 7, 8, 9]
print(data[1:4])
print(data[-1])
print(data[::-1])

Output:

[6, 7, 8]
9
[9, 8, 7, 6, 5]