LESSON 03 · BEGINNER PATH15 min

Lists

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.

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

Before you start: Variables and Types

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Lists

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    Suppose you want to keep track of several Python topics. You could create a separate variable for every topic, but that becomes awkward as the collection grows. A list lets one variable refer to an ordered sequence of values. In the starter code, topics holds strings, lists, and loops. Look at those three items before pressing Run. Python numbers positions from zero, so the first item is at index zero, the second at one, and the third at two. That numbering is unusual for a beginner, but it is consistent once you use it. In this lesson, we will read an item, add another one, replace an existing one, and understand why an append call should usually stand alone.

  2. 00:43

    We will also look at a queue, a slice, and a copy so you can tell what changes the list and what merely reads from it. At each step, pause and predict the state of the list. Tracing the collection after each line is much more reliable than memorizing a final output. When Python prints a whole list, its representation includes square brackets, commas, and quotation marks around string elements. When you print just one selected string, those surrounding list marks disappear. That difference does not mean the data changed; you asked print to display a different value. To check yourself, write the list after the initial assignment, after append, and after any replacement.

  3. 01:26

    This small trace becomes especially useful when later lessons combine lists with conditions and loops. Run the starter and follow the output in order. The square brackets in the assignment create the list. The expression topics at index zero reads strings, the first element, so the first print shows only that word. Then append adds functions at the end of the existing list. Printing topics now shows four elements, and len reports four. If you want the final element without calculating its positive index, use negative one. That means count back from the end, so it still works after you append more items.

  4. 02:06

    Assigning to topics at index zero replaces the first item because lists are mutable. It does not create a new list. The first deeper example uses a queue of work. A queue begins with intro and lists; append places loops at the end. Then pop at index zero removes and returns intro, the front item. The remaining list contains lists and loops. This is a useful pattern for small workloads, though very large queues often use a different collection for efficient front removal. The next guide example uses a slice. A slice from index one up to three takes positions one and two but stops before position three.

  5. 02:47

    It prints print and lists. A slice from the start to ten does not raise an error just because the list has fewer than ten elements; it returns the available items. That differs from asking for one nonexistent item at index ten. Finally, examine names and copies. If alias equals original, both names refer to the same list. Appending through alias changes what you see through original. Calling original dot copy creates a separate, shallow list copy. Appending files to that new copy does not add files to original. The distinction between an alias and a copy matters whenever two parts of a program share a mutable collection.

  6. 03:30

    The guide uses strings as list elements, so a shallow copy is enough to demonstrate independent list containers. If the elements themselves were nested mutable collections, that would need more care in a later lesson. Two common mistakes make these rules concrete. A list with three items has valid positive indexes zero, one, and two. Asking for index three raises IndexError because you are trying to read one position past the end. Print len of the list and remember that the last positive index is length minus one. A slice with a high stop can be harmless, but a single out-of-range index is not. The second mistake is writing items equals items dot append with a new value.

  7. 04:15

    Append changes the existing list in place and returns None. The assignment then makes items refer to None, so the next attempt to use it as a list fails. Call append on its own line, then print the list. This pattern of checking both the error message and the variable's current value makes a confusing bug much easier to locate. Now work on the practical task. Start with the topics list and append dictionaries. Replace the first item, strings, with variables by assigning to index zero. Finally, print only the last item using index negative one, rather than printing the whole list as the last output line.

  8. 04:55

    Before you run, say what the complete list should contain and what the final line should display. The task checker verifies the changed list and the way you selected the last item. If it does not pass, compare your current list with the requested contents. Did you accidentally append variables instead of replacing strings? Did you assign the return value of append? Did you print the entire list where only one item was requested? Make one correction at a time and rerun. The quiz reinforces three ideas: which item index one selects, what append returns, and how negative one finds the end. Try answering before you look at the options.

  9. 05:37

    As a small extension, add another topic after dictionaries and run again. The last-item expression should now follow the new end automatically. Once you can explain that behavior, you are ready to use lists in loops and projects where the number of items can change while the program runs.

Understand the concept

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.

03. Take a slice without changing the original

PYTHON
topics = ["strings", "lists", "loops", "functions"]
print(topics[1:3])
print(topics)
EXPECTED OUTPUT
['lists', 'loops']
['strings', 'lists', 'loops', 'functions']

The slice starts at index 1 and stops before index 3. It creates a new list while topics keeps all four items.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

Use a list as a queue of work

Lists are useful when a program must keep several related values in a chosen order. A short queue of lessons can gain an item at the end with append. The pop method can remove and return an item at a particular index. Removing index 0 means taking the first queued item, after which later items shift left.

Follow this queue through each change rather than memorizing a snapshot. The original list has two lessons, then a third is appended, then the first is removed. Predict the remaining list before running the code. Try changing pop(0) to pop() and notice that the default removes the last item instead.

PYTHON
queue = ["intro", "lists"]
queue.append("loops")
next_up = queue.pop(0)
print(next_up)
print(queue)
EXPECTED OUTPUT
intro
['lists', 'loops']
Follow the reasoning
  1. append places 'loops' after the existing items.
  2. pop(0) returns and removes the first item.
  3. The remaining list keeps its relative order.
02 / 03

A slice describes a range, not one index

An index selects one item; a slice selects a range. In items[start:stop], the start is included and the stop is excluded. This lets you use a count as the stop: items[:2] gets the first two items. A slice creates a new list, so it can be an easy snapshot of part of a larger collection.

Notice that asking for a slice past the end simply returns the available items, whereas direct indexing past the end raises IndexError. That difference makes slices practical for preview cards or a small first page of results. Predict whether topics[1:3] includes the item at index 3 before you run it.

PYTHON
topics = ["history", "print", "lists", "loops"]
print(topics[1:3])
print(topics[:10])
EXPECTED OUTPUT
['print', 'lists']
['history', 'print', 'lists', 'loops']
Follow the reasoning
  1. The first slice includes indexes 1 and 2, stopping before 3.
  2. The second slice starts at the beginning and safely stops at the list end.
  3. Both expressions produce new list values.
03 / 03

Shared names versus an independent copy

Two names can point to the same mutable list. Assigning alias = original does not copy its contents: changing the list through either name affects the single shared object. When you need a separate list that can diverge, call copy() or take a full slice. This matters when preserving an original plan while experimenting with a revised one.

In the example, the alias adds a topic to the original list. The copy is made afterward, so it starts with all three topics. Adding another item to the copy leaves the original alone. Before running the code, predict which list will contain 'files'. Then move the copy() call above the first append and reconsider the result.

PYTHON
original = ["intro", "lists"]
alias = original
alias.append("loops")
revised = original.copy()
revised.append("files")
print(original)
print(revised)
EXPECTED OUTPUT
['intro', 'lists', 'loops']
['intro', 'lists', 'loops', 'files']
Follow the reasoning
  1. alias and original refer to one list, so the first append is shared.
  2. copy() creates a second outer list with the current contents.
  3. Appending to revised changes only that second list.

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.

    Browse this lesson’s problem fixes