Skip to content
Lesson 6 of 10 · Python for Complete Beginners

Lists

Store many values in order, change them, loop over them and build new lists.

18 min

A list holds many values in order. Square brackets, commas between items:

python4 lines
scores = [72, 88, 95]
names = ["Ada", "Grace"]
mixed = [1, "two", 3.0]
empty = []

Lists use the same indexes and slices as strings: scores[0] is 72, scores[-1] is 95, scores[:2] is [72, 88]. Unlike strings, lists can be changed.

python5 lines
scores.append(60)        # add to the end
scores.insert(0, 50)     # add at a position
scores.remove(88)        # delete the first 88
last = scores.pop()      # remove and return the last item
scores[0] = 51           # replace by index

len(scores), sum(scores), max(scores), min(scores), sorted(scores) (a new sorted list), and scores.sort() (sorts in place and returns None). x in scores is True if the value is there.

python6 lines
doubled = []
for n in [1, 2, 3]:
    doubled.append(n * 2)

doubled = [n * 2 for n in [1, 2, 3]]            # same thing, one line
big = [n for n in [4, 9, 12] if n > 5]          # [9, 12]

Read a comprehension as "give me n * 2 for each n in the list". Use it when it stays readable on one line.

Common misconception

“`sorted_scores = scores.sort()` gives me a sorted copy.”

The name sounds like it produces a sorted list, and the line looks like it stores one.

What is actually true

.sort() changes the list in place and returns None, so sorted_scores would be None. To get a new sorted list and keep the original, use sorted(scores).

How to catch yourself

If a variable is unexpectedly `None`, check whether you saved the result of a method that changes in place (`sort`, `append`, `reverse`).

Lists and strings look alike but differ in one big way.

List

Index and slice
yes
Loop with `for`
yes
Can be changed after creation
yes
Holds
any values

Best for a collection you will add to, remove from or reorder

String

Index and slice
yes
Loop with `for`
yes
Can be changed after creation
no
Holds
characters only

Best for text

Exercise5 checks
python

Write top_three(scores) that returns the three highest scores, highest first. If there are fewer than three scores, return all of them, still highest first.

Your code must satisfy

  • top_three([5, 1, 9, 7])→[9,7,5]normal
  • top_three([4, 2])→[4,2]fewer than three
  • top_three([])→[]empty
  • top_three([3, 3, 3, 3])→[3,3,3]repeats count
  • top_three([1, 2, 3, 4, 5, 6])→[6,5,4]already sorted
starter code2 lines
def top_three(scores):
    pass
Exercise4 checks
python

Write evens_squared(numbers) that returns a new list of the squares of only the even numbers, in their original order. Try a list comprehension.

evens_squared([1, 2, 3, 4]) is [4, 16].

Your code must satisfy

  • evens_squared([1, 2, 3, 4])→[4,16]mixed
  • evens_squared([1, 3, 5])→[]all odd
  • evens_squared([-2, 5, 6])→[4,36]negatives
  • evens_squared([])→[]empty
starter code2 lines
def evens_squared(numbers):
    pass
  • A list is an ordered collection in [ ]; indexes and slices work like strings.
  • Lists can be changed: append, insert, remove, pop, and assigning by index.
  • sorted() returns a new list; .sort() changes the original and returns None.
  • A comprehension builds a new list in one line: [f(x) for x in items if test(x)].
Check yourself

List checks.

1Multiple choice

nums = [10, 20, 30] then nums.append(40). What is len(nums)?

  • A3
  • B4
  • C40
  • D2
2Multiple choice

What is [5, 6, 7, 8][1:3]?

  • A[5, 6]
  • B[6, 7]
  • C[6, 7, 8]
  • D[5, 6, 7]
3Multiple choice

What is [n * 2 for n in [1, 2, 3]]?

  • A[1, 2, 3, 1, 2, 3]
  • B[2, 4, 6]
  • C[2, 3, 4]
  • D6
4Numeric answer

xs = [4, 8, 15]. What is sum(xs) - max(xs)?

5Fill the blanks

To add 9 to the end of xs, write xs.(9).

Capitalisation, spacing and punctuation are ignored when grading.

For you · never graded

Choose a real list from your life (a shopping list, tasks, songs). What would you want a program to do with it: count, filter, sort, find the biggest?

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Python for Complete Beginners is planned around your week. Free.