Strings and sequences
Write a small program that transforms data using conditions, loops and functions.
THE IDEA
A string is an ordered row of characters
A string such as "model" is a sequence: its characters have a fixed order and each sits at a numbered position called an index. Python starts counting at zero, so the first character is at index 0 and a five letter word ends at index 4. Negative indexes count from the end: -1 is the last character.
Top number: index from the start. Bottom number: negative index from the end. Leave a box empty to mean "go to that end".
"transformer"[1:4] gives "ran"
The stop position is never included. Try 0 and 3, then 3 and 0 with step -1, then an empty start and stop with step -1.
Slicing: from start, up to but not including stop
text[a:b] takes the characters from index a up to, but not including, index b. That makes the length simply b - a, and it means text[:3] + text[3:] is always the whole text with nothing repeated or lost. A third number is the step, and a step of -1 walks backwards.
Predict first. What does "model"[1:4] give?
Strings cannot change. Lists can.
You cannot edit a string in place: word[0] = "T" raises TypeError: 'str' object does not support item assignment. To get a changed string you build a new one. A list is also a sequence, with the same indexing and slicing, but it can be changed in place with append or scores[0] = 75.
That power has a trap, which the name board makes visible. b = a never copies a list. It puts a second name on the same list.
Program (line 0 of 3)
a = [1, 2]b = ab.append(3)Names
no names yet
Objects in memory
no objects yet
Nothing has happened yet. No names, no objects.
Predict first. After a = [1, 2], b = a and b.append(3), what is a?
Chapter context
A program is a precise sequence of state changes. Python names refer to objects; reading a program means tracking the values those names refer to, rather than guessing from how the code sounds.
TRY IT YOURSELF
Exercise 1: pick a string apart
- Use only indexing and slicing on
word. Counting starts at 0, a negative index counts from the end, and a slices[a:b]stops just beforeb. - Your program is run again with a different word, so the code has to work for any word of at least four letters.
Exercise 2: a copy is not a second name
backupis meant to remember the original scores, butbackup = scoresonly puts a second label on the same list, so the changes below show up in both.- Fix the
backupline so it is a real, separate copy. Then addlast_two, the last two scores, with a slice.
Both exercises must be solved to finish this lesson.
Stuck, or something not working? You can come back to it any time.
CHECK YOUR UNDERSTANDING
Evaluate "model"[1:4].
Chapter reference: math, worked example & code
This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.
Math and notation
For an accumulator over numbers :
The subscript denotes a step, not a Python index. After the last step, is the sum. For a mean, divide by the number of items, and define what should happen for an empty list.
Worked example
Trace a robot's forward distances [2, 1, 3]. Position starts at zero and changes to 2, then 3, then 6. Replacing three copy-pasted moves with a loop preserves the order and final state. A mean distance is 6/3 = 2; the count is 3, not the last list index 2.
Reference code
The following example uses the Python standard library and does not call a remote service.
moves = [2, 1, 3]
position = 0
for distance in moves:
position += distance
assert position == 6
assert sum(moves) / len(moves) == 2
Python examples are provided for study and local execution; this page does not execute Python.
Common mistakes
Assignment does not copy a mutable object. A loop stop value is exclusive. A function can return None even when its print output looks correct.