This course builds data structures in Python. If you've done Programming basics, you know variables, lists, loops, functions and dictionaries. This lesson covers the few extra pieces the code here uses, starting with where data actually lives.
A computer's memory is a long row of numbered slots. Each slot holds one byte, which is 8 bits (eight 0s and 1s), enough for a number from 0 to 255. A slot's number is its address. Anything bigger than a byte takes several slots side by side: an 8-byte number stored at address 1000 fills addresses 1000 to 1007. A data structure is a way of laying values out in these slots and keeping track of where they are.
import brings in code that comes with Python but isn't loaded until you ask. import heapq lets you call heapq.heappush(), and from collections import deque brings in just deque, so you can use it by name.
A tuple is like a list in round brackets, (3, "tidy desk"), except it can't be changed once it's made. You can unpack one into several variables at once. Tuples compare item by item, first items first, so (1, "b") comes before (2, "a").
point = (3, 4)
x, y = point
print(x + y)
print((1, "b") < (2, "a"))
Prints
7
True
A class is a template for making your own kind of value, called an object. The __init__ function (two underscores on each side) runs when you make one and sets up its attributes, the named values it carries. Inside it, self means the object being set up. Outside, you read an attribute with a dot.
class Pet:
def __init__(self, name, legs):
self.name = name
self.legs = legs
p = Pet("Duck", 2)
print(p.name, p.legs)
Prints
Duck 2
None is Python's value for "nothing here". Test for it with x is None (is asks whether two names point at the very same thing). None also counts as false, so while node: keeps going until node becomes None.
Last, a function may call itself; that's called recursion. Each call works on a smaller piece and stops at a simple case it can answer straight away (the base case). The trees lesson uses it, and the Algorithms course covers it in depth.
def countdown(n):
if n == 0:
print("Go!")
return
print(n)
countdown(n - 1)
countdown(2)
Prints
2
1
Go!
Practice
An 8-byte number is stored starting at address 2000. What's the address of its last byte?
More info
Quick reference
byte, address
A byte is 8 bits; memory is a row of bytes, each with a numbered address.
import x / from x import y
Load a module that comes with Python, or one name from it.
(a, b)
A tuple: like a list, but can't be changed. `a, b = t` unpacks it.
class / __init__ / self
A template for objects; the setup function; the object being set up.
obj.attr
Read an object's attribute.
None, is None
"Nothing here", and the way to test for it.
Recursion
A function that calls itself on a smaller piece, down to a base case.