Making Decisions and Repeating Work

Lists


Learning Objectives

  • You can create a list and access items by index.
  • You can modify a list by index assignment, .append(), .pop(), and .remove().
  • You can use len() and in on a list.
  • You can predict the result of small list operations.

A study session by itself is one piece of information. The study log will eventually need to hold many sessions: today’s, yesterday’s, the previous part’s. A single variable cannot do that. A list can.

This chapter introduces lists. The next two chapters teach you how to do useful things with them.

A List Is an Ordered Collection

A list is a single value that contains many other values, in order. In Python, you write a list using square brackets and commas.

subjects = ["Math", "Physics", "Linear Algebra"]
minutes_list = [45, 30, 60]

The first variable holds a list of three strings. The second holds a list of three integers. Lists can hold any kind of value, and the items do not all have to be the same type — though in practice you usually want them to be, because mixing types makes the rest of your code harder to write.

You can print a list:

print(subjects)

This prints ['Math', 'Physics', 'Linear Algebra']. The single quotes around each string are how Python shows them; they are not part of the values.

A list can also be empty:

sessions = []

This is often how lists start. You begin with nothing, and add items as the program runs.

List literals

0 / 5 points

Which value is an empty list in Python?

Indexing

You access individual items of a list by their index — the position, starting from 0.

subjects = ["Math", "Physics", "Linear Algebra"]
print(subjects[0])
print(subjects[1])
print(subjects[2])

This prints Math, Physics, and Linear Algebra on three lines.

Index012
Value"Math""Physics""Linear Algebra"

This is the same indexing system you saw for strings in Part 1. The rules are the same too. A list of three items has valid indexes 0, 1, and 2. Asking for subjects[3] is an error — Python raises IndexError: list index out of range.

Negative indexes count from the end. subjects[-1] is the last item, subjects[-2] is the second-to-last, and so on. This is sometimes more convenient than counting from the front, especially when you want “whatever was just added”.

Indexes from both ends

0 / 5 points

What does this program print?

subjects = ["Art", "Math", "Biology"]
print(subjects[0])
print(subjects[-1])

Modifying a List by Index

Unlike strings, lists can be changed after they are created. You can replace an item by assigning to its index:

subjects = ["Math", "Physics", "Linear Algebra"]
subjects[0] = "Maths"
print(subjects)

This prints ['Maths', 'Physics', 'Linear Algebra']. The first item has been replaced. The list is the same list — same variable, same place in memory — but it now contains a different value at position 0.

This is a real difference between strings and lists, even though they share the indexing syntax. Try the equivalent on a string, and Python refuses:

word = "python"
word[0] = "P" # TypeError: 'str' object does not support item assignment

Strings cannot be modified in place. Lists can. You will see this distinction return in later parts of the course.

Replace a planned subject

0 / 10 points

The program starts with this list:

subjects = ["Math", "Physics", "History"]

Ask the user for a replacement subject. Replace the second item of the list with the user’s answer, then print the whole list.

Example input:

Art

Required output text:

['Math', 'Art', 'History']

Growing a List with .append()

The most common way to grow a list is with the .append(item) method. It adds one item to the end:

subjects = []
subjects.append("Math")
subjects.append("Physics")
print(subjects)

This prints ['Math', 'Physics']. Each .append adds one item, and the list grows by one each time.

This is the pattern your study log will use in this part’s project: start with an empty list, and append each new session as the user enters it.

A small but important detail: .append() modifies the list in place. It does not return a new list. Writing subjects = subjects.append("Math") is a bug — .append() returns None, so this line would replace the list with nothing. Just call subjects.append("Math") on its own line.

Append without losing the list

0 / 5 points

Arrange the lines into a program that appends two subjects and prints the list.

Removing Items

There are two common ways to remove an item.

.pop(i) removes and returns the item at position i. If you do not pass a position, it removes the last item.

subjects = ["Math", "Physics", "Linear Algebra"]
removed = subjects.pop()
print(removed)
print(subjects)

This prints Linear Algebra and then ['Math', 'Physics']. The list is one shorter, and the removed value was given back to you so you can use it if you need to.

.remove(value) removes the first item that equals the given value:

subjects = ["Math", "Physics", "Math"]
subjects.remove("Math")
print(subjects)

This prints ['Physics', 'Math'] — only the first "Math" was removed. Trying to remove a value that is not in the list raises a ValueError.

You will not need these often in this part, but they are useful to know.

Removing from a list

0 / 5 points

What is the difference between items.pop() and items.remove(value)?

len() and in

Two more operations come up almost every time you work with a list.

len(list) returns the number of items in the list. The same function works on strings.

subjects = ["Math", "Physics", "Linear Algebra"]
print(len(subjects))

This prints 3.

value in list is a Boolean expression. It evaluates to True if the value is in the list and False otherwise.

subjects = ["Math", "Physics"]
print("Math" in subjects)
print("Biology" in subjects)

This prints True and then False. This is the same Boolean machinery from Boolean Expressions, applied to a new operator. You can use it in an if:

if "Math" in subjects:
print("Math is one of the subjects.")

in also works for strings, where it asks “is this a substring of that one?”:

print("Math" in "Mathematics")

This prints True.

List length and membership

0 / 10 points

The program starts with this list:

subjects = ["Math", "Art", "History"]

Ask the user for a subject. Print the list length, then print whether the user’s subject is in the list.

Example input:

Art

Required output text:

Number of subjects: 3
Subject is planned: True

A Note on Empty Lists and Truthiness

An empty list [] acts like False when Python expects a Boolean, and a non-empty list acts like True. This means you can write:

if subjects:
print("There are subjects.")
else:
print("No subjects yet.")

The if subjects: here means “if subjects is not empty”. This is idiomatic Python, but it is also a place where readers and writers can disagree about clarity. The more explicit if len(subjects) > 0: is also fine. Use whichever feels clearer to you for now.

Common Pitfalls

A short list of mistakes that happen often at this stage:

  • Off-by-one. A list of three items has valid indexes 0, 1, and 2. Asking for [3] is one past the end.
  • IndexError. What Python raises when you ask for an index that does not exist.
  • subjects = subjects.append("Math"). A common mistake: .append() does not return the list. It returns None, and the line silently destroys the list. Write subjects.append("Math") on its own.
  • Confusing in for lists with in for strings. Both exist, both make sense, but "Math" in ["Mathematics"] is False — the list contains the single string "Mathematics", not the substring "Math".

Check Your Understanding

  1. Given numbers = [10, 20, 30, 40], what are the valid indexes?
  2. What is the difference between .pop() and .remove()?
  3. What is the value of len([])?
  4. What is the value of "Physics" in ["Math", "Physics", "Linear Algebra"]?
  5. Why is subjects = subjects.append("Math") a bug?