Chapter 8a - Lists
A list is an ordered collection. Use square brackets. Indexing starts at 0.
scores = [90, 85, 100]
names = ["Ada", "Lin", "Grace"]
mixed = [1, "two", True]
empty = []
π§ͺ Try it yourself
Change the list and print a different index.
Indexing and slicingβ
| Expression | Meaning |
|---|---|
items[0] | First element |
items[-1] | Last element |
items[1:3] | From index 1 up to (not including) 3 |
len(items) | How many elements |
π§ͺ Slicing
Mini quiz β lists and indexesβ
Lists and indexes
1 / 2What is fruits[1]?
fruits = ["apple", "banana", "cherry"]
Pick an answer to see if you are right.
Challenge: first and lastβ
Write ends(items) so it returns a new list with only the first and last values.
| items | Return |
|---|---|
[3, 1, 4, 1, 5] | [3, 5] |
["a", "b"] | ["a", "b"] |
Changing a listβ
Common methods:
| Method | Effect |
|---|---|
items.append(x) | Add x at the end |
items.pop() | Remove and return the last item |
items.insert(i, x) | Put x at index i |
items[i] = x | Replace the value at index i |
π§ͺ Growing a list
Looping through a listβ
for item in names:
print(item)
for i in range(len(names)):
print(i, names[i])
π§ͺ Loop
Mini quiz β mutate and loopβ
Mutate and loop
1 / 2What is nums after this?
nums = [1, 2]nums.append(3)
Pick an answer to see if you are right.
Challenge: sum of a listβ
Write total(nums) so it returns the sum of all numbers. Do not use sum().
| nums | Return |
|---|---|
1 2 3 | 6 |
10 -2 4 | 12 |
Exercisesβ
Activity: Largest number
Write largest(nums) so it returns the biggest value. Assume the list is not empty. Do not use max().
Expected for 3 9 2 9:
9