Python tutorials · Part 3 of 8

Python lists

A list is an ordered, changeable collection of values. It's the first data structure most Python programmers reach for. Here's everything you need to use lists confidently.

A list holds several values in order, inside square brackets. You can add to it, remove from it, sort it and change any item in place. If you need to keep "a bunch of things" together (scores, file names, rows of data), a list is usually where you start.

Creating a list

scores = [82, 74, 91, 68]
names = ["Asha", "Ben", "Chen"]
mixed = [1, "two", 3.0, True]
empty = []

print(len(scores), len(empty))
4 0

A list can hold any types, even mixed, but lists of one kind of thing are easier to work with. list() converts other iterables: list("abc") gives ['a', 'b', 'c'] and list(range(3)) gives [0, 1, 2].

Indexing: getting one item

Each item has a position, its index, starting at 0. Negative indexes count from the end:

names = ["Asha", "Ben", "Chen", "Dev"]
print(names[0])    # first
print(names[2])    # third
print(names[-1])   # last
print(names[-2])   # second to last
Asha
Chen
Dev
Chen

Asking for a position that doesn't exist, like names[10], raises IndexError: list index out of range.

Slicing: getting several items

A slice list[start:stop] returns a new list from start up to, but not including, stop. Leave either end out to mean "from the beginning" or "to the end":

nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[:3])
print(nums[3:])
print(nums[-2:])
print(nums[::2])
print(nums[::-1])
[20, 30, 40]
[10, 20, 30]
[40, 50, 60]
[50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]

The optional third number is the step: [::2] takes every second item and [::-1] reverses the list. Slicing never raises an IndexError; out-of-range slices just return fewer items.

Changing a list

Lists are mutable: you can change them in place.

fruits = ["apple", "pear"]
fruits.append("plum")          # add to the end
fruits.insert(0, "kiwi")       # add at a position
fruits.extend(["fig", "lime"]) # add several
fruits[1] = "mango"            # replace an item
print(fruits)
['kiwi', 'mango', 'pear', 'plum', 'fig', 'lime']

Removing items:

fruits = ["kiwi", "mango", "pear", "plum"]
fruits.remove("pear")   # by value (first match)
last = fruits.pop()     # remove and return the last item
first = fruits.pop(0)   # remove and return by index
print(fruits, last, first)
['mango'] plum kiwi

append adds one item, even if that item is a list; extend adds each item of another list. Mixing them up is a common bug: a.append([1, 2]) puts a whole list inside a.

Searching, counting and sorting

nums = [3, 1, 4, 1, 5, 9, 2]
print(4 in nums, nums.index(5), nums.count(1))
print(min(nums), max(nums), sum(nums))

print(sorted(nums))      # new sorted list
nums.sort(reverse=True)  # sorts in place, returns None
print(nums)
True 4 2
1 9 25
[1, 1, 2, 3, 4, 5, 9]
[9, 5, 4, 3, 2, 1, 1]

sorted(x) returns a new list and leaves x alone; x.sort() changes x and returns None. Both accept a key function: sorted(words, key=len) sorts by length.

Copying a list

Assignment doesn't copy; it gives the same list a second name:

a = [1, 2, 3]
b = a
c = a.copy()
a.append(4)
print(b, c)
[1, 2, 3, 4] [1, 2, 3]

a.copy(), list(a) and a[:] all make a shallow copy: a new outer list whose items are the same objects. For lists of lists, use copy.deepcopy() if you need fully independent copies.

List comprehensions

A list comprehension builds a new list from an existing iterable in one line: [expression for item in iterable if condition].

nums = [1, 2, 3, 4, 5, 6]
squares = [n * n for n in nums]
evens = [n for n in nums if n % 2 == 0]
labels = ["even" if n % 2 == 0 else "odd" for n in nums[:3]]
print(squares, evens, labels)
[1, 4, 9, 16, 25, 36] [2, 4, 6] ['odd', 'even', 'odd']

Use comprehensions for simple transformations and filters. If it needs more than one line to read, a regular for loop is clearer.

Lists of lists

A list can contain lists, which gives you a simple table:

grid = [[1, 2, 3], [4, 5, 6]]
print(grid[1][2])
print([row[0] for row in grid])
6
[1, 4]

For real tabular or numerical data, NumPy arrays and pandas DataFrames are faster and far more capable, but they're built on the same indexing ideas.

List, tuple or set?

All three hold several values, but they suit different jobs:

  • List: ordered and changeable. Use it for a sequence you'll add to, remove from or reorder.
  • Tuple: ordered but fixed. Use it for a record whose shape doesn't change, like a coordinate (x, y) or a function returning two values. Tuples can be dictionary keys; lists can't.
  • Set: no order and no duplicates. Use it when you only care whether something is present, or to remove duplicates. x in a_set stays fast however large the set is, while x in a_list gets slower as the list grows.

Common mistakes

  • Off-by-one indexing. The first item is [0] and the last is [-1] or [len(x) - 1].
  • x = x.sort(). sort() returns None, so this throws your list away. Use x.sort() or x = sorted(x).
  • append vs extend. append adds one item; extend adds many.
  • Modifying a list while looping over it. Items get skipped. Loop over a copy, or build a new list with a comprehension.
  • [[0] * 3] * 3 creates three references to the same inner list. Use [[0] * 3 for _ in range(3)].

Practice

  1. Reverse [1, 2, 3, 4] without using .reverse().
  2. From words = ["data", "ai", "model", "ml"], keep only words longer than 2 characters.
  3. Remove duplicates from [3, 1, 3, 2, 1] while keeping the first-seen order.

Answers

print([1, 2, 3, 4][::-1])

words = ["data", "ai", "model", "ml"]
print([w for w in words if len(w) > 2])

seen, unique = set(), []
for n in [3, 1, 3, 2, 1]:
    if n not in seen:
        seen.add(n)
        unique.append(n)
print(unique)
[4, 3, 2, 1]
['data', 'model']
[3, 1, 2]

Where this shows up in machine learning

Before data reaches NumPy or pandas, it's often a list: rows read from a file, file paths of images, the scores from each cross-validation fold. Slicing syntax carries straight over to NumPy arrays and pandas (X[:100], df.iloc[10:20]). And list comprehensions are everywhere in preprocessing code, such as cleaning a column of text with [t.lower().strip() for t in texts].

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.