Lesson 1 of 10
So far one variable has held one value. A list holds many, in order, in a single variable.
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(len(fruits))
Square brackets create a list, commas separate the items, and len() tells you how many there
are. A list can hold any type — even a mix, though in practice you usually keep one kind of
thing per list.
numbers = [4, 8, 15, 16]
mixed = ["Ada", 36, True]
empty = []
Indexing
Each item has a position, called its index. Python counts from 0, not 1.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
So the first item is [0] and the last item of a three-item list is [2]. Asking for
fruits[3] raises an IndexError — there is no fourth slot.
Negative indexes
Counting backwards from the end is common enough that Python builds it in. -1 is the last
item, -2 the second-to-last.
fruits = ["apple", "banana", "cherry"]
print(fruits[-1])
print(fruits[-2])
This saves you from writing fruits[len(fruits) - 1].
Changing an item
Unlike strings, lists are mutable — you can change them in place.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)
Slicing
A slice pulls out a section, using [start:stop]. As with range(), the stop is not
included.
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4])
print(numbers[:3])
print(numbers[3:])
print(numbers[-2:])
Leave out the start to mean "from the beginning," and leave out the stop to mean "to the end." A slice always gives you back a new list; the original is untouched.
Looping over a list
for walks a list the same way it walked a string in Module 2.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Try it yourself
Print the first item, the last item, and the middle two items of the list below.
Checkpoint
- Lists hold many ordered values:
[1, 2, 3]. - Indexes start at
0;-1is the last item. len()gives the length; an out-of-range index raisesIndexError.- Slices
[start:stop]exclude the stop and return a new list. - Lists are mutable — you can reassign an item by index.
Questions about this lesson
Log in to ask a question.