Lessons · Python · Quick reference
Python quick reference
168 topics, one line each, in the order Hone teaches them.
Hone is a place to practise programming. This sheet is the whole Python track at a glance: every idea it covers, in the order they are taught, one line each. It is a map rather than a lesson. Read opens the full explanation of an idea; Practise gives you a question on it. Both are free, and reading needs no account at all.
Your first code · Values and names
storing a value in a nameA name is a label you stick on a value so you can use it again later. Read: Storing a value in a name · Practise storing a value in a name
text vs numbers"5" and 5 are different things. Convert at the boundary with int() or float(), and never do arithmetic on the text. Read: Text that looks like a number is still text · Practise text vs numbers
turning a value into textstr(x) gives the text form of any value, so a number can sit inside a sentence. Read: Turning a value into text · Practise turning a value into text
text that should be a numberint('10') reads a string of digits and gives the number 10, so you can do maths on what a person typed. Read: Text that should have been a number · Practise text that should be a number
comments (# notes)A # starts a comment: Python ignores the rest of the line. It is for explaining why, not restating what. Read: Notes to the next reader, who is usually you · Practise comments (# notes)
Your first code · Doing things
calling a functionMost functions do a job and then give you a result. You have to catch the result or it is thrown away. Read: Functions hand something back · Practise calling a function
showing a value or handing it backprint writes to the screen and gives the caller nothing; return hands the value to whoever called the function. Read: Showing a value versus giving it back · Practise showing a value or handing it back
how long is this textlen(s) counts the characters in a string, spaces and punctuation included. Read: How long is this text · Practise how long is this text
one case to compare ins.lower() returns a new copy of the text in lowercase; the original string is untouched. Read: One case to compare in · Practise one case to compare in
cleaning and reshaping textStrings come with methods: strip, lower, split, replace, startswith. They return new strings; the original never changes. Read: Cleaning and reshaping text · Practise cleaning and reshaping text
Your first code · Numbers that behave
% the remaindera % b is what is left over after dividing a by b: 7 % 2 is 1. Read: The remainder · Practise % the remainder
// and %// gives how many whole times one number fits in another; % gives the remainder. Read: Whole parts and what is left over · Practise // and %
// whole-number divisiona // b divides and keeps the whole number, dropping the fraction: 7 // 2 is 3. Read: Whole-number division · Practise // whole-number division
** raising to a powera ** b raises a to the power b: 2 ** 3 is 8. It is not multiplication. Read: Raising to a power · Practise ** raising to a power
which operator goes firstMultiplication and division happen before addition and subtraction, so 3 + 4 * 2 is 11. Parentheses make the order explicit. Read: Which operator goes first · Practise which operator goes first
Your first code · Lists of things
the first item is item 0The first item is at position 0, not 1. Read: Counting from zero · Practise the first item is item 0
range()range gives you a run of numbers, starting where you say and stopping BEFORE the number you end with. Read: Counting a fixed number of times · Practise range()
counting from the endA negative index counts from the end: items[-1] is the last item, items[-2] the one before it. Read: Counting from the end · Practise counting from the end
build the list outside the loopCreate an empty list before the loop, append inside it, and use it after. One list, filled one item at a time. Read: Build the list outside the loop · Practise build the list outside the loop
list comprehensions[expression for item in items if condition] makes a new list from an old one: transform, filter, or both. Read: Build a list in one line · Practise list comprehensions
adding one thing or manyappend puts one item on the end; extend opens another list and pours its items in. Read: Adding one thing versus adding many · Practise adding one thing or many
Your first code · Deciding and repeating
if / elseif runs its block when the condition is true, and else runs when it is not. Exactly one of them happens. Read: Choosing between two paths · Practise if / else
returning True/FalseA comparison already IS a True or False; return it directly instead of wrapping it in if/else. Read: Returning the answer, not a description of it · Practise returning True/False
while loopswhile condition: repeats as long as the condition is true. Use it when you do not know in advance how many times. Read: Repeat until something changes · Practise while loops
enumerate (index + value)enumerate walks a list and hands you two things at once: where you are, and what is there. Read: Getting the position as well as the item · Practise enumerate (index + value)
in (is it inside?)in asks a yes or no question and answers True or False. Read: Asking whether something is there · Practise in (is it inside?)
Your first code · Looking things up
dict.get (missing keys)Square brackets demand a key and crash if it is missing. get asks politely and hands back None instead. Read: Asking for a key that might not be there · Practise dict.get (missing keys)
list or dict?A list is for things in order, reached by position; a dict is for things with a name, reached by key. Read: Position or name? · Practise list or dict?
sets remove duplicatesA set holds each value at most once, and checks membership instantly. Read: A collection that refuses duplicates · Practise sets remove duplicates
sorted() gives a new listsorted(xs) returns a new list in order and leaves xs alone. xs.sort() sorts in place and returns None. Read: A sorted copy · Practise sorted() gives a new list
slicing a[start:stop]seq[start:stop:step] gives the items from start up to but not including stop, without a loop. Negative numbers count from the end. Read: A window onto a sequence · Practise slicing a[start:stop]
Your first code · Objects that remember
classes (a blueprint)A class describes what a kind of thing has and does. Calling the class builds one object of that kind. Read: A class is a blueprint; an object is one thing made from it · Practise classes (a blueprint)
__init__ and self__init__ is the method Python calls on a new object. self is the object being built, and self.name = name stores a value on it. Read: __init__ runs when an object is built; self is that object · Practise __init__ and self
methods and attributesA method is a function defined inside the class. Calling d.bark() runs bark with self = d, so it can read and change that object's data. Read: Methods are functions that receive the object · Practise methods and attributes
__repr__ and __eq____repr__ decides how an object looks when printed or inspected. __eq__ decides what == means; without it, == asks whether two names point at the same object. Read: What an object shows, and when two are equal · Practise __repr__ and __eq__
inheritance and super()class Puppy(Dog) makes Puppy a kind of Dog: every Dog method works on a Puppy, and Puppy can add or override methods. super() reaches the parent's version. Read: A subclass gets the parent's methods and can change some · Practise inheritance and super()
dataclasses@dataclass reads the annotated fields and writes __init__, __repr__ and __eq__ for you. You declare what the object holds; Python writes how it is built, shown and compared. Read: A dataclass writes the boilerplate for you · Practise dataclasses
Read code you did not write · Which is which
two equal lists are not one list== asks whether two values match. is asks whether both names point at the very same object. Read: Same value, or the same thing · Practise two equal lists are not one list
== vs isEqual means the contents match; identical means one object. Two equal lists built separately are not identical, and 2 == 2.0 is True across types. Read: Why a is b can be False when a == b · Practise == vs is
copy or the same thing?b = a makes a second name for the same list. To get a separate list, copy it: list(a), a[:] or a.copy(). Read: Assignment does not copy · Practise copy or the same thing?
strings cannot be changedString methods hand back a NEW string. The original is never altered. Read: Text cannot be changed, only replaced · Practise strings cannot be changed
what counts as trueEmpty things are false. Anything with something in it is true. Read: What counts as true · Practise what counts as true
Read code you did not write · The traps
the def f(x=[]) trapA default value is created once, when the function is defined. If it is a list or dict, every call shares the same one. Read: The default argument that remembers · Practise the def f(x=[]) trap
changing a list while walking itRemoving items from a list inside a for loop over that same list skips items, because removal shifts everything after it one place left. Read: Do not change the list you are walking · Practise changing a list while walking it
two names, one listb = a does not copy a list. Both names point at the same one. Read: Two names for one list · Practise two names, one list
shallow vs deep copylist(x) or x[:] copies the outer list, but the items inside are the same objects. Nested lists are still shared. Read: A copy that is not all the way down · Practise shallow vs deep copy
lambdas look up lateA function made in a loop reads the loop variable when it is called, not when it was created, so every one sees the loop's final value. Read: A lambda looks up its variable when it runs · Practise lambdas look up late
Read code you did not write · What it costs
dict lookup is fastA dict jumps straight to a key; a list has to look at items one by one until it finds a match. Read: Why a dict finds things instantly · Practise dict lookup is fast
scanning a list is slowMany problems that look like they need to look backwards can be solved by walking forward once and remembering a single number. Read: One pass, one running fact · Practise scanning a list is slow
loop inside a loopIf the outer loop runs n times and the inner runs n times, the body runs n times n times. 1,000 becomes a million. Read: A loop inside a loop multiplies · Practise loop inside a loop
in: list vs setx in a_set is a direct lookup; x in a_list checks items one by one, so it slows down as the list grows. Read: Where 'in' is fast · Practise in: list vs set
memory for speedPrecomputing something once (a running total, a lookup table) can turn a repeated expensive calculation into one cheap read. Read: Spend memory to save time · Practise memory for speed
Read code you did not write · Say why
where a variable livesA variable made inside a function exists only there. Names from outside can be read, but assigning creates a new local one. Read: Where a name lives · Practise where a variable lives
checking for NoneNone means 'no value'. Check for it with 'is None', and check it before you use the thing. Read: Nothing is a value too · Practise checking for None
try / excepttry runs code that might fail; except catches a specific error and lets you decide what happens instead of crashing. Read: Plan for the failure · Practise try / except
bare exceptA bare except: catches everything, including typos, Ctrl-C and memory errors. Name the exception you mean: except ValueError:. Read: Catch the error you expect · Practise bare except
comparing decimals0.1 + 0.2 is 0.30000000000000004, so compare floats with a tolerance, never with ==. Read: Decimals that are almost equal · Practise comparing decimals
Read code you did not write · Prove it works
assertassert claim, message does nothing when the claim holds and raises AssertionError with the message when it does not. It is a sentence about your code that the computer checks. Read: assert says what must be true · Practise assert
a test functionA test is a plain function named test_something, with no arguments, that calls your code and asserts what should come back. pytest finds them by name and runs each one. Read: A test is a function that asserts one fact · Practise a test function
arrange, act, assertSet up the inputs, call the one thing being tested, check the result. Three short steps in that order, so a test can be read at a glance. Read: Arrange, act, assert · Practise arrange, act, assert
edge cases firstMost bugs live at the edges of the input: the empty case, the single item, all items equal, and the zero that divides. Test those first; the middle usually follows. Read: Test the ends first: nothing, one, everything the same · Practise edge cases first
Job-ready fundamentals · Reach for the right structure
look it up in a dictWalk the data once; store each thing you see in a dict keyed by what you will later need to look up. Read: Remember what you have seen, in a dict · Practise look it up in a dict
sorting with a keykey= tells sorted which part of each item to compare. To sort by two things, return a tuple. Read: Sort by the thing that matters · Practise sorting with a key
Job-ready fundamentals · The classics
searching sorted dataIn a sorted sequence, look at the middle: the target is either there, to the left, or to the right. Throw away half each time. Read: Halve the search space every step · Practise searching sorted data
a function that calls itselfA recursive function calls itself on a smaller input, and has a base case that stops it. Read: A problem defined by a smaller version of itself · Practise a function that calls itself
Job-ready fundamentals · Say it in the interview
saying the cost out loudName the time, name the space, and say where each comes from, in one breath: 'O(n) time because one pass; O(n) space because the set can hold every item.' Read: Say the cost out loud, before you are asked · Practise saying the cost out loud
naming the trade-offEvery choice gave something up. Say what you gained, what you paid, and why the gain matters for this problem. Read: Name both sides of the trade-off · Practise naming the trade-off
what to say when stuckSay three things, in order: what you know, what you are unsure about, and the small case you would try first. Then try it. Read: What to say when you are stuck · Practise what to say when stuck
the STAR storyA behavioural answer has four beats: the situation, the task you had, the action you took, the result that followed. Most of the words go on the action, and the result carries a number. Read: The two-minute story: Situation, Task, Action, Result · Practise the STAR story
Keep the edge · Deep water
dicts keep orderSince Python 3.7 a dict keeps keys in the order they were added. It is not sorted; it is remembered. Read: Dicts remember insertion order · Practise dicts keep order
generators run onceThings like map(), zip(), filter() and generator expressions produce values on demand; once you have walked to the end, they are empty. Read: A generator only runs once · Practise generators run once
*argsdef f(*args) collects every positional argument into a tuple, so f(1), f(1, 2, 3) and f() all work. Read: A function that takes any number of values · Practise *args
defaultdict adds keysd.setdefault(k, []) stores an empty list under k if k is missing and returns whichever list is now stored, so appending to it changes the dict. Read: setdefault hands you the stored object · Practise defaultdict adds keys
why 256 is 256Python keeps one shared copy of small integers, so a is b can be True for 5 and False for 5000. It is an implementation detail, not a rule. Read: Why 'is' flickers on numbers · Practise why 256 is 256
Keep the edge · Money and time
money is whole centsFloats cannot hold 0.1 exactly, so sums of prices drift. Store money as integer cents (or Decimal) and format to whole units only for display. Read: Money is whole cents · Practise money is whole cents
a time that knows its timezoneA naive datetime carries no timezone; an aware one does. Python refuses to subtract one from the other, because the answer would be a guess. Read: A time that knows where it is · Practise a time that knows its timezone
round() sends halves to evenround() sends an exact .5 to the nearest even number: round(2.5) is 2 and round(3.5) is 4. The errors cancel over a long column. Read: Rounding halves to even · Practise round() sends halves to even
do not compare decimals with ==0.1 + 0.2 == 0.3 is False, because neither side is stored exactly. Compare floats with a tolerance: math.isclose. Read: Do not compare floats with == · Practise do not compare decimals with ==
Keep the edge · Data at scale
deduplicating recordsset(records) fails on dicts because they are unhashable. Deduplicate by building a key that identifies a record, a tuple of normalised fields, and keeping the first row per key. Read: Deduplicating records · Practise deduplicating records
stable sortingPython's sort is stable: items that compare equal keep their original order. Sort by the secondary key first, then by the primary, and ties stay ordered. Read: Sort by two things · Practise stable sorting
when a join multiplies rowsJoining one order to its three items gives three rows, each carrying the order's amount. That is correct, and it means summing amount afterwards counts the order three times. Read: When a join multiplies rows · Practise when a join multiplies rows
rows with no key vanish from a group-byGrouping by a field drops rows where that field is missing, so group totals add up to less than the column total, and nothing says why. Read: Rows with no key vanish from a group-by · Practise rows with no key vanish from a group-by
comprehension variablesIn Python 3 the loop variable of a comprehension lives inside it. After [x for x in range(3)], x outside is whatever it was before, or undefined. Read: A comprehension keeps its variable to itself · Practise comprehension variables
Data structures and algorithms · Things in a line
linked listsA linked list is not one block of memory. It is small objects, each holding a value and a reference to the next one, ending at None. Read: Nodes that point at the next node · Practise linked lists
stacks and queuesA stack hands back what you put in most recently; a queue hands back what has waited longest. A Python list is already a stack; use collections.deque for a queue. Read: Last in first out, and first in first out · Practise stacks and queues
two pointersInstead of comparing every pair with two nested loops, put one index at each end and move them toward each other, deciding at each step which one to move. Read: Two fingers, one pass · Practise two pointers
the sliding windowKeep a start and an end over the same sequence. The end always moves forward; the start moves forward only when the window has broken a rule. The items between them are the window. Read: A window that grows and shrinks · Practise the sliding window
Data structures and algorithms · Things in a grid
grids (a list of lists)grid[row][col]. The outer list holds rows, so the first bracket picks a row and the second picks a cell inside it. Read: A grid is a list of lists · Practise grids (a list of lists)
Data structures and algorithms · Things in a tree
binary treesA binary tree node holds a value and at most two children. In a binary SEARCH tree, everything left of a node is smaller and everything right is larger. Read: A node, a left and a right · Practise binary trees
walking a treeDepth-first goes all the way down one branch before trying the next, and recursion does it for free. Breadth-first goes level by level, and needs a queue. Read: Two ways to visit every node · Practise walking a tree
Data structures and algorithms · Things in an order
what sorting costssorted() costs about n log n and is stable: items that compare equal keep the order they already had. That stability is a feature you can build on. Read: What sorting costs, and what it buys · Practise what sorting costs
heaps (the smallest first)A heap keeps only enough order to know its minimum. heapq.heappush and heapq.heappop each cost about log n, and the smallest is always at index 0. Read: Always hand me the smallest · Practise heaps (the smallest first)
Data structures and algorithms · Things joined to things
graphs (things joined to things)A graph in Python is usually a dict from each node to the list of nodes it joins. Unlike a tree it can contain cycles, so every walk needs a set of what it has already seen. Read: Things joined to things · Practise graphs (things joined to things)
memoising (not doing it twice)When a recursion asks the same smaller question down more than one branch, store each answer the first time. The code barely changes; the cost changes class. Read: Remember what you already worked out · Practise memoising (not doing it twice)
greedy choicesA greedy algorithm makes the choice that looks best at each step and never reconsiders. That is why it is fast, and why it is sometimes wrong. Read: Take the best step now, and never look back · Practise greedy choices
More
any() and all()any() asks 'is at least one true?', all() asks 'are they all true?', over a whole list in one line. Read: Asking a question of every item at once · Practise any() and all()
a < b < cQuestions on Hone; no lesson yet. Practise a < b < c
the first line of a CSVQuestions on Hone; no lesson yet. Practise the first line of a CSV
commas inside a quoted fieldQuestions on Hone; no lesson yet. Practise commas inside a quoted field
dates as text that still sortQuestions on Hone; no lesson yet. Practise dates as text that still sort
De Morgan's lawsQuestions on Hone; no lesson yet. Practise De Morgan's laws
a merge that drops rowsQuestions on Hone; no lesson yet. Practise a merge that drops rows
mean() skips the missingQuestions on Hone; no lesson yet. Practise mean() skips the missing
fixing types at the boundaryQuestions on Hone; no lesson yet. Practise fixing types at the boundary
dict comprehensionsQuestions on Hone; no lesson yet. Practise dict comprehensions
looping over a dictfor k in d gives keys; d.values() gives values; d.items() gives (key, value) pairs. Read: Walking a dict: keys, values, or both · Practise looping over a dict
dividing by zeroQuestions on Hone; no lesson yet. Practise dividing by zero
sum and max of nothingQuestions on Hone; no lesson yet. Practise sum and max of nothing
enumerate(start=1)Questions on Hone; no lesson yet. Practise enumerate(start=1)
putting values into textf"...{value}..." drops a value into a string where the braces are, with optional formatting after a colon. Read: Putting values into text · Practise putting values into text
guard clausesQuestions on Hone; no lesson yet. Practise guard clauses
JSON keys come back as textQuestions on Hone; no lesson yet. Practise JSON keys come back as text
dict keys must not changeQuestions on Hone; no lesson yet. Practise dict keys must not change
not (a or b)Questions on Hone; no lesson yet. Practise not (a or b)
nested .get()Questions on Hone; no lesson yet. Practise nested .get()
or hands back a valueQuestions on Hone; no lesson yet. Practise or hands back a value
text with a thousands commaQuestions on Hone; no lesson yet. Practise text with a thousands comma
abs()Questions on Hone; no lesson yet. Practise abs()
any()Questions on Hone; no lesson yet. Practise any()
True counts as 1Questions on Hone; no lesson yet. Practise True counts as 1
bool(0)Questions on Hone; no lesson yet. Practise bool(0)
get() with a defaultQuestions on Hone; no lesson yet. Practise get() with a default
dict(a=1)Questions on Hone; no lesson yet. Practise dict(a=1)
{k: v for ...}Questions on Hone; no lesson yet. Practise {k: v for ...}
divmod()Questions on Hone; no lesson yet. Practise divmod()
True and 1 are the same keyQuestions on Hone; no lesson yet. Practise True and 1 are the same key
list(enumerate(...))Questions on Hone; no lesson yet. Practise list(enumerate(...))
filter()Questions on Hone; no lesson yet. Practise filter()
formatting to two decimalsQuestions on Hone; no lesson yet. Practise formatting to two decimals
summing a generatorQuestions on Hone; no lesson yet. Practise summing a generator
int() with base 0Questions on Hone; no lesson yet. Practise int() with base 0
'-'.join(...)Questions on Hone; no lesson yet. Practise '-'.join(...)
[[0]] * 3 shares one listQuestions on Hone; no lesson yet. Practise [[0]] * 3 shares one list
[x for x in ...]Questions on Hone; no lesson yet. Practise [x for x in ...]
a comprehension with an ifQuestions on Hone; no lesson yet. Practise a comprehension with an if
map()Questions on Hone; no lesson yet. Practise map()
// rounds down, not toward zeroQuestions on Hone; no lesson yet. Practise // rounds down, not toward zero
flattening with a comprehensionQuestions on Hone; no lesson yet. Practise flattening with a comprehension
1 == TrueQuestions on Hone; no lesson yet. Practise 1 == True
list(range(n))Questions on Hone; no lesson yet. Practise list(range(n))
counting down with rangeQuestions on Hone; no lesson yet. Practise counting down with range
reduce()Questions on Hone; no lesson yet. Practise reduce()
[::-1] reversesQuestions on Hone; no lesson yet. Practise [::-1] reverses
reversed()Questions on Hone; no lesson yet. Practise reversed()
a set drops repeatsQuestions on Hone; no lesson yet. Practise a set drops repeats
| joins two setsQuestions on Hone; no lesson yet. Practise | joins two sets
[::2] every other oneQuestions on Hone; no lesson yet. Practise [::2] every other one
sorting by lengthQuestions on Hone; no lesson yet. Practise sorting by length
sorting a dict's itemsQuestions on Hone; no lesson yet. Practise sorting a dict's items
sorted(reverse=True)Questions on Hone; no lesson yet. Practise sorted(reverse=True)
split()Questions on Hone; no lesson yet. Practise split()
'ab' * 3Questions on Hone; no lesson yet. Practise 'ab' * 3
slicing a stringQuestions on Hone; no lesson yet. Practise slicing a string
sum()Questions on Hone; no lesson yet. Practise sum()
title()Questions on Hone; no lesson yet. Practise title()
tuple()Questions on Hone; no lesson yet. Practise tuple()
zip()Questions on Hone; no lesson yet. Practise zip()
the base caseQuestions on Hone; no lesson yet. Practise the base case
leave as soon as you knowreturn ends the function immediately. Returning early for the simple cases keeps the main path unindented and clear. Read: Leave as soon as you know · Practise leave as soon as you know
naming a variable listQuestions on Hone; no lesson yet. Practise naming a variable list
and/or stop earlyQuestions on Hone; no lesson yet. Practise and/or stop early
sorting when one value is NoneQuestions on Hone; no lesson yet. Practise sorting when one value is None
sort() vs sorted()list.sort() sorts the list itself and returns None; sorted(x) leaves x alone and returns a new sorted list. Read: Sorting in place versus sorting a copy · Practise sort() vs sorted()
join (pieces to text)",".join(pieces) puts the separator between every item and returns one string. The separator is what you call it on. Read: From pieces to one string · Practise join (pieces to text)
truth tablesQuestions on Hone; no lesson yet. Practise truth tables
tuples cannot changeQuestions on Hone; no lesson yet. Practise tuples cannot change
opening a fileQuestions on Hone; no lesson yet. Practise opening a file
zip (walk two lists)zip(a, b) pairs items by position, so one loop can use both. Read: Walking two lists together · Practise zip (walk two lists)