Python Basics · Lesson 9 of 12

Lists

A list holds several values in order. It is written in square brackets:

fruits = ["apple", "banana", "cherry"]

Positions start at zero

Each item has a position, called its index. The first item is at index 0:

print(fruits[0])     # apple
print(fruits[2])     # cherry
print(fruits[-1])    # cherry: negative numbers count from the end
print(len(fruits))   # 3

Replace an item by assigning to its index: fruits[1] = "blueberry".

Changing a list

CodeWhat it does
fruits.append("kiwi")adds an item to the end
fruits.insert(0, "fig")adds an item at a position
fruits.remove("apple")removes the first matching item
fruits.pop()removes the last item and returns it
fruits.sort()sorts the list in place
"kiwi" in fruitsTrue if the item is in the list

Looping over a list

This is where for shines. The loop variable takes each item in turn:

for fruit in fruits:
    print(fruit)

Helpful functions

For lists of numbers, Python has sum(), min() and max() built in:

scores = [70, 85, 92]
print(sum(scores))                 # 247
print(sum(scores) / len(scores))   # the average

Slices

fruits[0:2] gives a new list with the items from index 0 up to, but not including, index 2.

Your Task

  1. Add "Saturn" to the end of the planets list with a method.
  2. Change the first item from "Mercury" to "Venus".
  3. Use a for loop to print every planet on its own line.
  4. After the loop, print how many planets are in the list.
  • "Saturn" is added to the end with append
  • The first item is now "Venus"
  • A for loop prints all four planets in order
  • The number of planets, 4, is printed last