Find a course

Module 4: Lists, Dictionaries and Other CollectionsLesson 9 of 1213 min

Lists

Create and change lists, sort them correctly, understand why two names can share one list, and build new lists quickly with list comprehensions.

Step 1 of 14Learn

Many values under one name

A weather app records a temperature every day for a month. Thirty variables named temp1 to temp30 would be miserable to work with. A list holds all of them under one name, in order:

temps = [18.5, 21.0, 19.2, 23.8]
names = ["Ana", "Ben", "Cy"]
mixed = [42, "hello", True, 3.5]   # allowed, but usually a sign of messy design
empty = []

Lists use square brackets with items separated by commas. Everything you learned about string indexing and slicing works the same way:

  • temps[0] is 18.5 (indexes start at 0) and temps[-1] is 23.8.
  • temps[1:3] is [21.0, 19.2], a new list.
  • len(temps) is 4.
  • 19.2 in temps is True.

The big difference from strings: lists are mutable, meaning you can change them in place. temps[0] = 17.9 replaces the first value; with a string, that would be an error.

Lists also work beautifully with the tools you already know. for t in temps: walks through them; sum(temps) / len(temps) gives the average; max(temps) finds the hottest day. And temps.index(23.8) tells you the position of a value (raising a ValueError if it isn't there).

Step 2 of 14Learn

Adding, removing and changing items

Lists come with methods for changing their contents:

CodeEffect on items = ["a", "b", "c"]
items.append("d")adds to the end: ["a", "b", "c", "d"]
items.insert(0, "z")inserts at index 0: ["z", "a", "b", "c"]
items.extend(["d", "e"])adds several items to the end
items.remove("b")removes the first "b": ["a", "c"]
items.pop()removes and returns the last item, "c"
items.pop(0)removes and returns the item at index 0
del items[1]deletes the item at index 1
items[1] = "B"replaces the item at index 1
items.clear()empties the list

A few behaviors worth knowing:

  • remove() deletes by value and only the first match; it raises a ValueError if the value isn't present. Check with if x in items: first.
  • pop() deletes by position and gives you the item back, which is handy for processing a to-do list.
  • append() adds exactly one item. items.append(["d", "e"]) adds a single item that is itself a list, giving ["a", "b", "c", ["d", "e"]]. Use extend() to add each element separately.

The common pattern for building a list is to start empty and append in a loop: evens = [], then inside for n in range(10):, if n % 2 == 0: evens.append(n).

Step 3 of 14Flashcards

List methods on ["a", "b", "c"]

Tap a card to flip it.

Step 4 of 14Practice · What would you do?

What would you do?

What does this program print?

cart = ["milk", "bread"]
cart.append("eggs")
cart.insert(0, "coffee")
cart.remove("bread")
print(cart)

Step 5 of 14Learn

Sorting: sort() versus sorted()

There are two ways to sort, and confusing them is a classic bug.

list.sort() sorts the list in place and returns None:

scores = [72, 95, 61]
scores.sort()
print(scores)          # [61, 72, 95]

sorted(list) leaves the original alone and returns a new sorted list:

scores = [72, 95, 61]
ranked = sorted(scores, reverse=True)
print(ranked)          # [95, 72, 61]
print(scores)          # [72, 95, 61]  (unchanged)

The bug: scores = scores.sort(). The list does get sorted, but then the name scores is reassigned to the return value, None, and your data seems to vanish. Remember: methods that change a list in place (sort, append, reverse, remove) return None.

Both accept reverse=True for descending order and a key function that decides what to sort by. sorted(names, key=len) sorts by length; sorted(names, key=str.lower) sorts alphabetically while ignoring case. Without that, "Zoe" comes before "adam", because uppercase letters sort before lowercase ones.

Sorting needs comparable items: a list mixing numbers and strings raises a TypeError when sorted.

Step 6 of 14Compare

sort() vs sorted()

Aspectlist.sort()sorted(list)
Changes the original?Yes, in placeNo
ReturnsNoneA new sorted list
Works onLists onlyAny iterable: strings, tuples, sets
Reverse orderscores.sort(reverse=True)sorted(scores, reverse=True)

Step 7 of 14Practice · True or false

After nums = [3, 1, 2], the line result = nums.sort() makes result equal to [1, 2, 3].

Step 8 of 14Learn

Two names, one list: mutability and aliasing

Remember that variables are labels on values. With numbers and strings, that detail rarely matters, because they can't be changed in place. With lists, it matters a lot:

a = [1, 2]
b = a            # b is a second label on the SAME list
b.append(3)
print(a)         # [1, 2, 3]  surprise!

b = a doesn't copy anything. Both names refer to one list, so a change made through either name is visible through both. This is called aliasing.

When you want an independent copy, make one explicitly:

b = a.copy()     # or a[:] or list(a)
b.append(3)
print(a)         # [1, 2]   unchanged

Aliasing also explains why a function can change a list you pass to it: the function receives a label on your list, not a copy. That's sometimes exactly what you want (a function that adds an item to a cart) and sometimes a nasty surprise.

Note that reassigning is different from modifying. b = [9, 9] moves the label b to a brand-new list and leaves a alone. Only operations that change the list itself, such as append, sort, b[0] = ... or remove, are seen through every alias.

Step 9 of 14Diagram

Two labels, one list

Two labels, one listParts diagram: One list: [1, 2, 3], Label a, Label b.One list: [1, 2,3]Label aLabel b

Tap a shape with to see more.

b = a.copy() would create a second, independent list instead.
One list: [1, 2, 3]
Label a

Created by a = [1, 2].

Label b

b = a adds a second label. b.append(3) changes the list both labels share.

Step 10 of 14Practice · Choose one

What does a = [1, 2]; b = a; b.append(3); print(a) print?

Step 11 of 14Learn

List comprehensions: build a list in one line

Building a new list from an old one is so common that Python has a compact syntax for it, the list comprehension:

prices = [10, 25, 40]
with_tax = [p * 1.08 for p in prices]         # [10.8, 27.0, 43.2]

Read it as "p times 1.08, for each p in prices". It does exactly what this loop does:

with_tax = []
for p in prices:
    with_tax.append(p * 1.08)

You can add a condition to keep only some items:

scores = [72, 95, 61, 88]
passing = [s for s in scores if s >= 70]      # [72, 95, 88]
names = ["  ana ", "BEN", " cy"]
clean = [n.strip().title() for n in names]    # ['Ana', 'Ben', 'Cy']

The pattern is always [expression for item in collection if condition], with the condition optional.

Comprehensions are fast and, once you're used to them, very readable for simple transformations and filters. Don't force everything into one: if the logic needs several steps, multiple conditions or nested loops, a regular for loop with a clear name for each step is easier for the next person to understand, and that person is often you, three months later.

Step 12 of 14Practice · Code challenge · Python

Complete above_average(numbers) so it returns a new list with only the numbers that are strictly greater than the average of the list, in their original order. If the list is empty, return an empty list.

Real Python, running in a sandbox in your browser.
  • above_average([4, 8, 6, 2])
  • above_average([10, 10, 10])
  • above_average([1.5, 3.5])
  • above_average([])

Step 13 of 14Practice · Fill in the blanks

Fill in the blanks

The comprehension [n * n for n in range(1, 4)] produces [1, 4, ], and [w for w in ["a", "bb", "ccc"] if len(w) > 1] produces a list with items.

Step 14 of 14Practice · Match the pairs

Match each operation on a list to its effect.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. items.append(x)
  2. items.extend(other)
  3. items.pop()
  4. items.remove(x)
  5. sorted(items)