Lesson ยท 10 min
Lists
Many values in one name
A list keeps values in order. You write it with square brackets and commas.
colors = ["red", "green", "blue"]
scores = [10, 7, 9]
A list can hold any kind of value.
Reading items
Each item has a position, called an index. The first index is 0. Python also counts from the end with negative numbers: -1 is the last item.
print(colors[0]) # red
print(colors[2]) # blue
print(colors[-1]) # blue
print(len(colors)) # 3
Changing a list
| Code | What it does |
|---|---|
colors.append("pink") |
adds an item to the end |
colors.pop() |
removes the last item and gives it to you |
colors.remove("red") |
removes the first item that matches |
colors.sort() |
puts the items in order |
"red" in colors |
is True when the item is in the list |
", ".join(colors) |
joins text items into one text |
Unlike a string, a list can change. A method such as append changes the list that you already have.
Going through a list
A for loop gives you each item, one after the other.
for color in colors:
print(color)
Slices
A slice takes a part of a list. colors[0:2] takes the items at positions 0 and 1. The end position is not included.
Your turn
The list fruits is already in the editor. Write your code under it. Some tasks depend on the tasks before them.
Tasks
6 to do
Task 1, not checked yet. Make a variable
secondthat holds the second item offruits.Task 2, not checked yet. Add the text
'date'to the end offruits. Use theappendmethod.Task 3, not checked yet. Make a variable
countthat holds the number of items infruits, and a variablelastthat holds the last item. Write them after theappendline.Task 4, not checked yet. Use a
forloop to print each fruit in capital letters, one on each line.Task 5, not checked yet. Make a variable
textthat joins the items offruitsinto one text, with' and 'between the items. Use thejoinmethod of the separator.Task 6, not checked yet. Make a variable
has_cherrythat isTruewhen'cherry'is infruits. Use theinoperator.
Task 1 of 6
Make a variable second that holds the second item of fruits.