Python

Lesson 6 of 10

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

  1. Task 1, not checked yet. Make a variable second that holds the second item of fruits.

  2. Task 2, not checked yet. Add the text 'date' to the end of fruits. Use the append method.

  3. Task 3, not checked yet. Make a variable count that holds the number of items in fruits, and a variable last that holds the last item. Write them after the append line.

  4. Task 4, not checked yet. Use a for loop to print each fruit in capital letters, one on each line.

  5. Task 5, not checked yet. Make a variable text that joins the items of fruits into one text, with ' and ' between the items. Use the join method of the separator.

  6. Task 6, not checked yet. Make a variable has_cherry that is True when 'cherry' is in fruits. Use the in operator.

Task 1 of 6

Make a variable second that holds the second item of fruits.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.