Skip to content

Python Foundations·Lesson 5 of 67·beginner

Lists

The ordered, mutable collection you will reach for more than any other — building it, changing it, slicing it, and knowing when it is the wrong tool.


In this lesson · 15 min

  • →Create, index and slice lists
  • →Add, remove, sort and reverse items
  • →Understand that a list is a reference, not a copy
  • →Write your first list comprehension

A list holds an ordered collection of anything, and unlike a string, you can change it in place.

PythonPython not started

Lists are heterogeneous — Python does not require the items to share a type:

PythonPython not started

In practice you almost always want a list of one kind of thing. A list of mixed types usually means the data should have been a dictionary.

Changing a list

PythonPython not started

Searching and counting

PythonPython not started

index raises a ValueError if the value is not there, so check with in first when you are not sure.

Sorting

There are two ways, and the difference matters.

PythonPython not started

sorted() works on anything iterable and leaves the original alone. .sort() is a list method that mutates. A common mistake is numbers = numbers.sort(), which sets numbers to None.

Sorting by a computed key is where it gets useful:

PythonPython not started

Slicing works exactly as it does on strings

PythonPython not started

A list is a reference

This catches everyone once. Assigning a list to a new name does not copy it.

PythonPython not started

Building lists with a loop — then without one

The long way:

PythonPython not started

The Python way — a list comprehension:

PythonPython not started

Read it left to right: the expression, for each item, if the condition holds. It is shorter, and — because Python does the looping internally — usually faster.

Try it yourself

Exercise 1

Print the three highest scores in descending order, as a list.

Your turnPython not started
Exercise 2

Build passing: the names of every model scoring 0.85 or better, in the original order. Use a list comprehension.

Your turnPython not started

Check yourself

After numbers = [3, 1, 2] and result = numbers.sort(), what is result?

Recap

  • Lists are ordered, mutable and can hold anything.
  • append adds one item, extend adds many, pop removes and returns.
  • sorted(x) returns a new list; x.sort() mutates and returns None.
  • Assignment shares a list; use x[:] or list(x) to copy.
  • A list comprehension is the idiomatic way to build a list from another sequence.
Next: Dictionaries →