LESSON 03 · BEGINNER PATH10 min

Lists

Create a list, access its items, and change its contents.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

Understand the concept

A list keeps values in an ordered collection. Index 0 is the first item, and index -1 is the last item. Square brackets select an item or a slice.

Lists can change after creation. Use append() to add an item, or assign to an existing index to replace one. The len() function reports how many items a list contains.

  • Indexes begin at 0
  • Lists are mutable
  • append() adds one item

See it step by step

Read the code, predict the output, then compare it with the result.

01. Append a topic

PYTHON
topics = ["strings", "loops"]
topics.append("dictionaries")
print(topics)
EXPECTED OUTPUT
['strings', 'loops', 'dictionaries']

append() puts one new value at the end of the existing list.

02. Replace and inspect

PYTHON
colors = ["red", "blue", "green"]
colors[0] = "yellow"
print(colors[-1])
print(len(colors))
EXPECTED OUTPUT
green
3

Index 0 changes the first item; index -1 reads the last item. The list still has three items.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnAdd "dictionaries" to the topics list, replace "strings" with "variables", and print the last item.
Need a hint?

Use topics.append('dictionaries') to grow the list. Replace the item at index 0 with 'variables', then print(topics[-1]).

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.What is [10, 20, 30][1]?

    02.What does items.append(4) return?

    03.What does ["a", "b", "c"][-1] select?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Index past the end

    COMMON MISTAKE
    items = ["a", "b"]
    print(items[2])
    FIX
    items = ["a", "b"]
    print(items[1])

    What happens: IndexError because the only valid positive indexes are 0 and 1.
    The final positive index is len(items) - 1.

    Saving append's return value

    COMMON MISTAKE
    items = [1, 2]
    items = items.append(3)
    print(items)
    FIX
    items = [1, 2]
    items.append(3)
    print(items)

    What happens: The variable becomes None.
    Call append without assigning its return value.