Lists

Lists in Python represent ordered sequences of values.

1
primes = [2, 3, 5, 7]

Types of things in list

1
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

A list of list

1
2
3
4
5
6
7
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 contains different types of variables

1
2
my_favourite_things = [32, 'raindrops on roses', help]
# (Yes, Python's help function is *definitely* one of my favourite things)

Indexing

1
planets[0]

‘Mercury’

Elements at the end of the list can be accessed with negative numbers, starting from -1:

1
planets[-1]

Slicing

What are the first three planets?
前三个行星是什么?

1
planets[0:3]

[‘Mercury’, ‘Venus’, ‘Earth’]

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:
起始索引和结束索引都是可选的。所以我可以把上面的表达式改写成:

1
planets[:3]

[‘Mercury’, ‘Venus’, ‘Earth’]