PYTHON / CHAPTER 03

Lists and changing one item

Beginner

Build an ordered collection and use indexes to inspect or update it.

By the end of this chapter

  • Create a list literal
  • Read a zero-based list index
  • Append an item without replacing the list

The idea

A list stores several values in order inside square brackets. Commas separate the items: labels = ["read", "code"]. The first position is zero, so labels[0] is "read". len(labels) counts items. For a nonempty list, labels[-1] reads the last item; an empty list has no valid item to read.

Lists are mutable. labels[0] = "review" replaces one item, while labels.append("test") adds an item at the end. append changes the list and returns None; it does not return the updated list. Keep the original variable and call the method on its own statement.

A list is a useful input for a loop or function. First practice tracing a small list manually: write its positions, change one item, then append another. Later chapters explain sets, dictionaries, copying, and shared references. You can learn the basic container before those extra rules.

Python example
labels = ["read", "code"]
labels[0] = "review"
labels.append("test")
print(labels[0])
print(len(labels))
print(labels[-1])
Result
review
3
test

Replacing index zero keeps two items. Appending adds a third, which can be read with the negative index -1.

Try it yourself

Make a list of two numbers. Replace the second number, append a third, and print the list and its length.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open Python coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which statement appends a label while keeping labels as a list?