Summary

In this lesson, you learned that:

  • A list stores several values, its elements, in one variable, in a fixed order: names = ["Anna", "Tom"]. An empty list is [].
  • print(names) prints the list in square brackets, with commas, and with text in single quotes: ['Anna', 'Tom']. To print it with a label, use a comma or an f-string: print("Names:", names). Joining text and a list with + ends with a TypeError.
  • Each element has an index, counted from 0. names[0] reads the first element, names[1] = "Lucy" changes the second one. Negative indexes count from the end: names[-1] is the last element. Asking for an index where there is no element ends with IndexError: list index out of range.
  • The function len(names) gives you the number of elements. The last index is len(names) - 1.
  • A method is a function that belongs to a value, written after a dot. append() adds an element to the end of a list. pop() removes the last element, or the one at the index in the parentheses, and returns it. remove() removes the first element with a given value; removing a value that isn't in the list ends with a ValueError.
  • value in names is True if the list contains the value, and value not in names is True if it doesn't. Both are most often used with if.
  • A list can contain other lists, called nested lists: groups[1][0] is the first element of the second inner list.
  • A text isn't a list, but you can read its characters by index (name[0], name[-1]) and get its length with len(). You can't change its characters: name[0] = "X" ends with a TypeError.

In the next lesson, on loops, you'll learn to repeat code, for example to go through all the elements of a list one by one, however many there are. But first, practice what you know on a shopping list.

Instructions

Write an if statement: if item isn't in shopping yet (use not in), add it to the end of the list with append().

You still have some bread at home: remove "bread" from the list. Then print the number of items and the last item with an f-string, so that the output is Items: 3, last: butter. Get the number with len() and the last item with a negative index. (Once this step passes, try changing item to "milk": milk is already on the list, so it isn't added again.)

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

12/12