iq.lab
Python starts when a code cell comes near or you run one
01 Python, one step at a time

Lesson 1 of 6

Names, values and lists

A name is a tag tied to a value, and `=` moves the tag. A list is a row of numbered boxes you can read, slice and change, and two names can share one list, which is sometimes what you want and sometimes a bug.

About 1 hour 10 minutes
By the end you can
  • Read any assignment the way Python runs it, right side first, and say the value of every name afterwards

  • Choose between /, // and %, and predict their results

  • Read and change a list by position, including negative positions

  • Say exactly which items a slice holds

  • Tell a second name for a list from a copy of it, and make a copy when you need one

Here is a line you have read many times: count = count + 1. As algebra it is false, since no number equals itself plus one. In Python it is not a fact. It is an instruction: work out count + 1, then make the name count refer to the answer.

Interview code is built from a handful of moves like that one: give a value a name, read an item of a list, change an item, cut out a piece. When every move is exact in your head, you can run a short program on paper, line by line, which is what a round without a run button asks of you.

You have used all of these before. This lesson makes each one exact and shows it running in a trace.

A name is a tag on a value

What does = do? A name (Python calls it a variable) is a tag tied to a value. x = 5 makes the value 5 and ties the tag x to it. Later lessons also say a name "points at" or "refers to" its value; that is the same tag.

Every assignment (a line of the form name = something) runs in the same order: work out the right side first, then tie the name on the left to the result.

Before you step through, guess what the last line prints (print(x, y) prints both values on one line, with a space between). Press Next to run one line at a time. Next to the code, the Names panel lists every name and the value its tag is tied to. Above the code, the change line says what the line that just ran changed.

Step throughMoving a name to a new value
Step 1 of 5
Line 1 is about to run.
Make the value 5 and tie the name x to it.
x = 5
y = x
x = x + 1
print(x, y)
Names
no names yet
Output
(nothing printed yet)

y = x does not tie y to x. It ties y to the value x has at that moment, and moving x later leaves y where it was. Moving a name to a new value is called rebinding. x = x + 1 rebinds x, and Python has a shorthand for it: x += 1.

Try it on four lines in a row. Keep a small table on paper, one column per name.

PredictRight side first

Read the four assignments in order and type exactly what the program prints, one value per line.

a = 4
b = a + 2
a = b * 3
b = b - a
print(a)
print(b)

Five kinds of value

Every value has a type: the kind of thing it is, which decides what you can do with it. Interview code uses five types almost everywhere:

TypeWhat it holdsExamplesWhere you meet it
inta whole number0, 42, -7counts, sums, positions in a list
floata number with a decimal point2.5, 4.0, float("inf")averages, and a start value bigger than every number
strtext, in quotes"cat", "" (empty)words, characters, keys
boolTrue or False3 > 2 is Trueanswers to yes or no questions
Noneno value at allNone"nothing found yet", or a function with nothing to hand back

Three rows of that table need a word more. A decimal point makes a float: 4.0 is a float even though its value is whole. A comparison is a question, and its answer is a bool: 3 > 2 is True, and x == 6 is True only when x is 6.

None is Python's "no value", the job NULL does in a table: it marks that nothing is known yet. Unlike NULL, it compares normally: None == None is True. When you are unsure of a type, ask Python: print(type(2.5)) prints <class 'float'>.

Three ways to divide

Dividing whole numbers is where types matter first. Python has three division operators, and each answers a different question. (An operator is a symbol that combines two values, like +.) Take 17 divided by 5:

  • / divides fully and always gives a float: 17 / 5 is 3.4.
  • // gives the whole part: how many whole times 5 fits into 17, with the remainder dropped. 17 // 5 is 3. Its name is floor division, because it rounds down to a whole number.
  • % gives the remainder (read it "mod"): 17 % 5 is 2, because three 5s make 15 and 2 are left over.

These rules are for positive numbers, the only kind in this lesson. Lesson 6 shows what // does with a negative one.

The pair % 10 and // 10 is a classic: together they peel the last digit off a number. Before you step, guess what 472 % 10 is.

Step throughPeeling off digits with % and //
Step 1 of 8
Line 1 is about to run.
n = 472
print(n / 10)
last = n % 10
n = n // 10
last = n % 10
n = n // 10
print(n, last)
Names
no names yet
Output
(nothing printed yet)

/ gives a float even when it divides evenly: 8 / 2 is 4.0, not 4. And % has two everyday jobs: x % 2 == 0 asks whether x is even (no remainder after dividing by 2), and n % 10 is the last digit of n.

PredictThree ways to divide

Type exactly what this prints, one line per print. When print gets two values separated by a comma, it prints them on one line with a space between.

print(7 / 2)
print(7 // 2)
print(7 % 2)
print(9 / 3)
print(365 // 7, 365 % 7)

A list is a row of numbered boxes

A list holds values in order, in a row of numbered boxes. You write it in square brackets: nums = [12, 30, 7, 25, 18]. The box numbers are called positions, or indexes, and they start at 0. nums[i] reads the item in box i, so the first item is nums[0]. len(nums) counts the items.

Before you step through, decide: what is the position of the last box in a list of five? The arrow labelled i under the list shows which box i points at.

Step throughReading a list by position
Step 1 of 8
Line 1 is about to run.
Five values in five numbered boxes.
nums = [12, 30, 7, 25, 18]
n = len(nums)
i = 0
first = nums[i]
i = n - 1
last = nums[i]
also_last = nums[-1]
Names
no names yet
Output
(nothing printed yet)

Three rules come out of that trace:

  • Positions run from 0 to len(nums) - 1. There is no box at len(nums). On this list, nums[5] raises an error: Python stops the program and reports IndexError: list index out of range. The empty list [] has no boxes at all, so even position 0 fails.
  • Negative positions count from the end. nums[-1] is the last item and nums[-2] the one before it. Python reads nums[-k] as nums[len(nums) - k].
  • Positions must be ints. nums[len(nums) / 2] raises a TypeError even when the length is even, because / always gives a float. For a middle position, write len(nums) // 2.

Reading nums[i] takes one step however long the list is, because Python goes straight to the box. Module 3 shows how a list makes that possible.

Work it outCounting from the end

With nums = [6, 11, 9, 14, 20, 3], what is nums[-2]? Type the value.

nums[-2]

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Slices: a piece of a list

Often you want several neighboring boxes at once: the first three days, or everything but the last. nums[start:stop] builds a new list from position start up to, but not including, position stop. Before you step, guess how many items nums[1:3] holds.

Step throughCutting out a slice
Step 1 of 7
Line 1 is about to run.
nums = [12, 30, 7, 25, 18]
start = 1
stop = 3
piece = nums[start:stop]
head = nums[:2]
tail = nums[2:]
Names
no names yet
Output
(nothing printed yet)

The rule in one line: inside the list, a slice nums[start:stop] holds stop - start items. Leave out start and it begins at 0; leave out stop and it runs to the end. Negative positions work in slices too: nums[-2:] is the last two items.

A slice that runs past the end is not an error. It keeps the items that exist: on this list, nums[3:100] is [25, 18]. In SQL terms, nums[start:stop] is LIMIT stop - start OFFSET start on an ordered result.

A slice is a new list. Changing piece afterwards would not touch nums. That fact comes back at the end of this lesson as the standard way to copy a list.

PredictWhich boxes does a slice keep?

Type exactly what this prints. A list prints in square brackets with a comma and a space between items, like [10, 20].

nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[3:])
print(nums[1:-1])
print(len(nums[1:4]))

Now combine len, // and a slice. The lines below form a function: def gives a short program a name and an input, and return hands back its answer. Lesson 3 covers functions properly; here you only put the lines in order.

Put in orderThe middle three

Put the lines in order to build middle_three(nums), which returns a new list holding the middle item of nums and its two neighbors. nums has an odd number of items, at least three. Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return nums[start:start + 3]
    • start = middle - 1
    • middle = len(nums) / 2
    • def middle_three(nums):
    • return nums[start:start + 2]
    • middle = len(nums) // 2

    So far: a name is a tag on a value, and = moves the tag. / gives a float, // the whole part and % the remainder. A list is a row of boxes numbered from 0: nums[i] reads one box, nums[-1] reads the last, and nums[start:stop] copies stop - start boxes into a new list. Next, changing the boxes.

    Changing a list in place

    Can a value change after it is made? A number cannot: x = x + 1 makes a new number and moves the tag. A list can. nums[1] = 9 puts a new value into box 1 of the same list, and nums.append(25) adds a new box at the end. Both change the list in place: no new list is made, and the list itself now holds different values.

    Writing needs a box that already exists. On a three-item list, nums[3] = 25 raises an IndexError. To add a box at the end, use append.

    The trace below changes one box, appends one, and then tries to swap the first and last items. Before you step, predict what it prints.

    Step throughChanging a list in place
    Step 1 of 7
    Line 1 is about to run.
    nums = [12, 30, 7]
    nums[1] = 9
    nums.append(25)
    nums[0] = nums[-1]
    nums[-1] = nums[0]
    print(nums)
    Names
    no names yet
    Output
    (nothing printed yet)

    Writing into a box throws away what was there. That is why the swap failed: by the time line 5 ran, the 12 had been overwritten. The fix is one extra name that keeps the old first item safe before box 0 changes. You saw this work in the first trace, where y kept the old 5 while x moved on. In words: save the first item as first, copy the last item into box 0, then copy first into the last box.

    Module 0 introduced four questions this course asks of every algorithm: the walk (the order we visit the data), the notebook (what we write down as we go), the promise (what the notebook means after every step) and the cost (the time and memory it takes). The extra name first is the swap's notebook. The fixed swap is a tiny algorithm, so here it is in those terms:

    Now write the fixed swap. Python also has a one-line swap, which lesson 5 shows; it saves both old values before changing either, the same idea in one line.

    Code itSwap the first and last items

    Write swap_ends(nums), which swaps the first and last items of nums in place (it changes the list it is given) and then returns nums. The list has at least one item. Use a notebook name, as in the frame card above. Then press Watch it run and find the step where your notebook saves the first item.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Two names, one list

    In the first trace, y = x gave the number 5 two tags. That was harmless, because a number cannot change. With a list it matters: b = a does not copy the list. It ties a second tag to the same list, so a change made through either name shows through both. This is called aliasing. Before you step, guess what line 4 prints.

    Step throughTwo names, one list
    Step 1 of 8
    Line 1 is about to run.
    a = [1, 2, 3]
    b = a
    b.append(4)
    print(a)
    c = a[:]
    c.append(5)
    print(a, c)
    Names
    no names yet
    Output
    (nothing printed yet)

    Changing a list and rebinding a name are different moves. b.append(4) and b[0] = 9 change the list b names, so a sees them. b = [7, 7] moves the tag b to a new list and leaves a's list alone.

    For an independent copy, slice everything, a[:], or call list(a). A copy takes one step per item, so make one when you need it, not by habit. The copy is one level deep: if a list holds other lists, its copy holds the same inner lists. Lesson 6 shows that kind of sharing inside a grid.

    Passing a list to a function gives the function one more tag on your list. Its input name is a second name for the list you passed, which is why swap_ends changed the very list it was given. In module 11 you will save a copy of a list instead of the list itself, for exactly this reason.

    Quick checkChange or rebind?

    What does this program print?

    a = [3, 6, 9]
    b = a
    b[0] = 1
    b = [5, 5]
    b.append(2)
    print(a)

    Choose one answer, then check.

    Now use a copy on purpose. A function that fixes one value should not quietly change a list that other code still reads.

    Code itA corrected copy

    Yesterday's order counts are in a list that other code still reads. Write corrected(counts, i, value), which returns a new list equal to counts except that position i holds value. The list passed in must not change. i is a valid position, and may be negative.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

    Last, practice the tracing out loud. The words you write here are the words you will say in the room.

    Say itTrace it out loud

    In a round with no run button, you test code by reading it aloud with the value of every name. Do that for this program: after each line, say what changed and why.

    nums = [5, 1, 4]
    nums[0] = nums[0] + nums[2]
    nums.append(nums[1] * 2)
    draft = nums[:]
    draft[-1] = 0
    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Walking a list