Skip to main content

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​

ExpressionMeaning
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​

Quiz

Lists and indexes

1 / 2

What 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.

itemsReturn
[3, 1, 4, 1, 5][3, 5]
["a", "b"]["a", "b"]

Changing a list​

Common methods:

MethodEffect
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] = xReplace 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​

Quiz

Mutate and loop

1 / 2

What 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().

numsReturn
1 2 36
10 -2 412

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