← Back to course
Code Crew G5 / Week 01 / Monday
1/6
Week 01 Β· Crew check

Monday

Lists and spot numbers
// The tools you already have
⏱ about 15 min

Monday: Lists and spot numbers

The fleet glides into a new star cluster. Thousands of points of light sparkle in every window.

"Our job is to map it," Rocket says. "I will start the star catalog right now!" He types five names into a list.

Nova projects the list in glowing blue letters. Rocket points at the first name. "That one is star number 1."

Raven tilts her head. "What do you notice about the spot numbers Nova shows?"

Nova blinks her cyan lights. "Here is a hint. Count the way Python counts."

A list keeps things in order

A list holds many values under one name. Square brackets wrap the list. Commas go between the values.

Each value sits in a spot called an index. Python starts counting spots at 0, not 1.

stars = ["Ember", "Frost", "Glow", "Halo", "Iris"]
print(stars[0])
print(stars[3])
print(len(stars))
print(stars[-1])
Output:
Ember
Halo
5
Iris
Index01234
StarEmberFrostGlowHaloIris
  • stars[0] is the first item, because counting starts at 0.
  • len(stars) counts the items. Five items means the spots go from 0 to 4.
  • stars[-1] is a shortcut for the last item, whatever the length.
What does print(stars[1]) show?
What does print(stars[4]) show?
What does print(stars[2]) show?

Adding to a list

The append() tool adds a new item to the end of a list. The list grows by one.

stars = ["Ember", "Frost", "Glow"]
stars.append("Juno")
print(len(stars))
print(stars[-1])
PREDICT THE OUTPUT OF THE PROGRAM ABOVE.
  • Read the question.
  • Tap your answer.
What does the first print show?
What does the second print show?
Statement about stars = ["Ember", "Frost", "Glow", "Halo", "Iris"]True or false?
stars[0] is "Ember".?
stars[5] is "Iris".?
len(stars) is 5.?
stars[-1] is "Iris".?
WHY THIS EXERCISEAsking for a spot past the end is a common bug. Python stops with an IndexError.

Practice lab: the probe list

probes = ["Kit", "Ivo", "Sol"]
probes.append("Bea")
probes[1] = "Max"
print(probes)
print(len(probes))
print(probes[-2])
What does len(probes) show?
What does probes[-2] show?
What is probes[1] at the end?
Which index holds "Bea"?
LIST CHECK
  • Read the question.
  • Tap your answer.
What does probes[0] give?
Which line stops with an IndexError?
What does append do?
Statement about probesTrue or false?
probes[1] = "Max" replaced "Ivo".?
len(probes) is 3 at the end.?
probes[-1] is "Bea".?
append can only add numbers.?
WHY THIS EXERCISETracing a list line by line keeps every index straight.
nums = [5, 8]. Then nums.append(nums[0] + nums[1]) runs. What is nums[-1]?
WHY THIS EXERCISEThe value inside the brackets is worked out first, then appended.

Great start, Crew Engineer! Lists are the backbone of the star catalog. Tomorrow we loop through a list and add things up.