Lists in Python represent ordered sequences of values. Here is an example of how to create them:
primes = [2, 3, 5, 7]
We can put other types of things in lists:
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
We can even make a list of lists:
hands = [ ['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K'], # (Comma after the last element is optional) ] # (I could also have written this on one line, but it can get hard to read) hands = [['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K']]
A list can contain a mix of different types of variables:
my_favourite_things = [32, 'raindrops on roses', help] # (Yes, Python's help function is *definitely* one of my favourite things)
You can access individual list elements with square brackets.
Which planet is closest to the sun? Python uses zero-based indexing, so the first element has index 0.
What's the next closest planet?
Which planet is furthest from the sun?
Elements at the end of the list can be accessed with negative numbers, starting from -1:
What are the first three planets? We can answer this question using slicing:
planets[0:3] is our way of asking for the elements of
planets starting from index 0 and continuing up to but not including index 3.
The starting and ending indices are both optional. If I leave out the start index, it's assumed to be 0. So I could rewrite the expression above as:
If I leave out the end index, it's assumed to be the length of the list.
i.e. the expression above means "give me all the planets from index 3 onward".
We can also use negative indices when slicing:
# All the planets except the first and last planets[1:-1]
# The last 3 planets planets[-3:]
# Changing lists
Lists are "mutable", meaning they can be modified "in place".
One way to modify a list is to assign to an index or slice expression.
For example, let's say we want to rename Mars:
planets = 'Malacandra' planets
Hm, that's quite a mouthful. Let's compensate by shortening the names of the first 3 planets.
planets[:3] = ['Mur', 'Vee', 'Ur'] print(planets) # That was silly. Let's give them back their old names planets[:4] = ['Mercury', 'Venus', 'Earth', 'Mars',]
# List functions
Python has several useful functions for working with lists.
len gives the length of a list:
# How many planets are there? len(planets)
sorted returns a sorted version of a list:
# The planets sorted in alphabetical order sorted(planets)
sum does what you might expect:
primes = [2, 3, 5, 7] sum(primes)
We've previously used the
max to get the minimum or maximum of several arguments. But we can also pass in a single list argument.
# Interlude: objects
I've used the term 'object' a lot so far - you may have even read that everything in Python is an object. What does that mean?
In short, objects carry some things around with them. You access that stuff using Python's dot syntax.
For example, numbers in Python carry around an associated variable called
imag representing their imaginary part. (You'll probably never need to use this unless you're doing some very weird math.)
x = 12 # x is a real number, so its imaginary part is 0. print(x.imag) # Here's how to make a complex number, in case you've ever been curious: c = 12 + 3j print(c.imag)
The things an object carries around can also include functions. A function attached to an object is called a method. (Non-function things attached to an object, such as
imag, are called attributes).
For example, numbers have a method called
bit_length. Again, we access it using dot syntax:
To actually call it, we add parentheses:
Aside: You've actually been calling methods already if you've been doing the exercises. In the exercise notebooks
q3, etc. are all objects which have methods called
In the same way that we can pass functions to the
help function (e.g.
help(max)), we can also pass in methods:
The examples above were utterly obscure. None of the types of objects we've looked at so far (numbers, functions, booleans) have attributes or methods you're likely ever to use.
But it turns out that lists have several methods which you'll use all the time.
# List methods
list.append modifies a list by adding an item to the end:
# Pluto is a planet darn it! planets.append('Pluto')
Why does the cell above have no output? Let's check the documentation by calling
appendis a method carried around by all objects of type list, not just
planets, so we also could have called
help(list.append). However, if we try to call
help(append), Python will complain that no variable exists called "append". The "append" name only exists within lists - it doesn't exist as a standalone name like builtin functions such as
-> None part is telling us that
list.append doesn't return anything. But if we check the value of
planets, we can see that the method call modified the value of
list.pop removes and returns the last element of a list:
# Searching lists
Where does Earth fall in the order of planets? We can get its index using the
It comes third (i.e. at index 2 - 0 indexing!).
At what index does Pluto occur?
Oh, that's right...
To avoid unpleasant surprises like this, we can use the
in operator to determine whether a list contains a particular value:
# Is Earth a planet? "Earth" in planets
# Is Calbefraques a planet? "Calbefraques" in planets
There are a few more interesting list methods we haven't covered. If you want to learn about all the methods and attributes attached to a particular object, we can call
help() on the object itself. For example,
help(planets) will tell us about all the list methods:
Click the "output" button to see the full help page. Lists have lots of methods with weird-looking names like
__iadd__. Don't worry too much about these for now. (You'll probably never call such methods directly. But they get called behind the scenes when we use syntax like indexing or comparison operators.) The most interesting methods are toward the bottom of the list (
Tuples are almost exactly the same as lists. They differ in just two ways.
1: The syntax for creating them uses parentheses instead of square brackets
t = (1, 2, 3)
t = 1, 2, 3 # equivalent to above t
2: They cannot be modified (they are immutable).
t = 100 #'tuple' object does not support item assignment
Tuples are often used for functions that have multiple return values.
For example, the
as_integer_ratio() method of float objects returns a numerator(分子) and a denominator(分母) in the form of a tuple:
x = 0.125 x.as_integer_ratio()
These multiple return values can be individually assigned as follows:
numerator, denominator = x.as_integer_ratio() print(numerator / denominator)
Finally we have some insight into the classic Stupid Python Trick™ for swapping two variables!
a = 1 b = 0 a, b = b, a # 交换值 print(a, b)
# Exercise: Lists
Try the hands-on exercise (opens new window) with lists and tuples
Complete the function below according to its docstring.
def select_second(L): """Return the second element of the given list. If the list has no second element, return None. """ if len(L) < 2: return None return L # return L if len(L) >=2 else None q1.check()
You are analyzing sports teams. Members of each team are stored in a list. The Coach is the first name in the list, the captain is the second name in the list, and other players are listed after that. These lists are stored in another list, which starts with the best team and proceeds through the list to the worst team last. Complete the function below to select the captain of the worst team.
def losing_team_captain(teams): """Given a list of teams, where each team is a list of names, return the 2nd player (captain) from the last listed team """ return teams[-1] q2.check()
The next iteration of Mario Kart will feature an extra-infuriating new item, the Purple Shell. When used, it warps the last place racer into first place and the first place racer into last place. Complete the function below to implement the Purple Shell's effect.
def purple_shell(racers): """Given a list of racers, set the first place racer (at the front of the list) to last place and vice versa. >>> r = ["Mario", "Bowser", "Luigi"] >>> purple_shell(r) >>> r ["Luigi", "Bowser", "Mario"] """ temp = racers[-1] racers[-1] = racers racers = temp q3.check()
What are the lengths of the following lists? Fill in the variable
lengths with your predictions. (Try to make a prediction for each list without just calling
len() on it.)
a = [1, 2, 3] b = [1, [2, 3]] c =  d = [1, 2, 3][1:] # Put your predictions in the list below. Lengths should contain 4 numbers, the # first being the length of a, the second being the length of b and so on. lengths = [len(a),len(b),len(c),len(d)] q4.check()
- a: There are three items in this list. Nothing tricky yet.
- b: The list
[2, 3]counts as a single item. It has one item before it. So we have 2 items in the list
- c: The empty list has 0 items
- d: The expression is the same as the list
[2, 3], which has length 2.
# 5. 🌶️
We're using lists to record people who attended our party and what order they arrived in. For example, the following list represents a party with 7 guests, in which Adela showed up first and Ford was the last to arrive:
party_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford']
A guest is considered 'fashionably late' if they arrived after at least half of the party's guests. However, they must not be the very last guest (that's taking it too far). In the above example, Mona and Gilbert are the only guests who were fashionably late.
Complete the function below which takes a list of party attendees as well as a person, and tells us whether that person is fashionably late.
def fashionably_late(arrivals, name): """Given an ordered list of arrivals to the party and a name, return whether the guest with that name was fashionably late. """ order = arrivals.index(name) return order >= len(arrivals) / 2 and order != len(arrivals) - 1 q5.check()