Night 6: Your pet's favourite snacks
Tonight: a list of snacks
- Your pet likes many snacks. One variable for each? Too many!
- You will learn one thing: lists.
Words for tonight
| Word | Meaning |
|---|---|
| list | many values in one variable, in order |
| item | one value in a list |
| position | where an item is; Python starts at 0 |
Make a list
- Use square brackets
[ ]. - Put a comma between the items.
snacks = ["apple", "rice", "fish"]
print(snacks)
Python counts from 0
| Position | 0 |
1 |
2 |
|---|---|---|---|
| Item | "apple" |
"rice" |
"fish" |
- Write the position in square brackets after the name.
snacks = ["apple", "rice", "fish"]
print(snacks[0])
print(snacks[1])
Add and count
.append( )adds a new item at the end.len( )tells you how many items there are.
snacks = ["apple", "rice"]
snacks.append("cake")
print(snacks)
print(len(snacks))
Change one item
- Put a new value at a position with
=.
snacks = ["apple", "rice", "fish"]
snacks[0] = "pear"
print(snacks)
- Careful:
snacks[3]gives an IndexError here. There is no position 3.
Now you try
- Do the tasks below. Press Run, then Check answer.
- Tomorrow your pet will use this list in a loop.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Make a list called snacks with three items: "apple", "rice" e "fish", in this order.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Print the primeiro snack, then the último snack. The output is apple and then fish, on two lines.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Your pet found a new snack. Add "cake" to the end of the list with .append( ). Then print how many snacks there are with len( ). The output is 4.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Your pet does not like rice any more. Change the segundo item to "noodles". Then print the whole list.
Clique em Executar para ver a saída aqui.