Python Arena

Topics A to Z

Python keywords, functions, methods, types and ideas from the lessons, A to Z, each in one line with the steps that teach it. It's a map of this course, not all of Python: for every function and module, see Python's library reference.

Operators and symbols

A

B

C

  • call stack

    idea

    The unfinished function calls that Python keeps waiting, the newest on top, each carrying on when the call above it returns.

  • chained comparison

    idea

    A comparison such as 1 <= x <= 10 that compares the value in the middle with both limits at once.

  • character class

    idea

    Square brackets in a regular expression, such as [aeiou] or [0-9], which match one character of those listed.

  • clamping

    idea

    Keeping a value between a lowest and a highest allowed value, for example a position inside the window with max(0, min(x, WIDTH - 40)).

  • class

    keyword

    Defines a class, the blueprint for a kind of object: the attributes its objects get and the methods they have.

  • class hierarchy

    idea

    Classes that inherit one another over several levels, like a family tree, where an object is also an instance of every class above its own.

  • class variable

    idea

    A variable written in a class outside its methods, shared by all objects of the class and used through the class's name.

  • @classmethod

    function

    A decorator that makes a method belong to the class, so it's called through the class's name and gets the class as cls.

  • client

    idea

    The code that uses an object by creating it and calling its methods.

  • cls

    idea

    The usual name of a class method's first parameter, which refers to the class itself, so cls(...) creates a new object.

  • collections.Counter

    type

    A dict that counts. Counter(values) maps each value to how often it appears, a missing value counts as 0, and most_common(k) gives the k most common.

  • collections.deque

    type

    A queue that adds and removes items at both of its ends in O(1), with append and popleft, where a list's pop(0) is O(n).

  • collections.OrderedDict

    type

    A dict that moves a key to its end with move_to_end(key) and removes its first pair with popitem(last=False), both in O(1) on average.

  • collision detection

    idea

    Finding out whether two things in a game touch, such as the robot and a coin, often by checking whether their rectangles overlap.

  • combination

    idea

    A choice of k items in which the order doesn't matter; a search makes each one only once by picking the items in increasing order.

  • comparison operator

    idea

    One of ==, !=, <, <=, > and >=, which compare two values and give True or False.

  • concatenation

    idea

    Joining strings end to end with +, which puts nothing between them, not even a space.

  • conditional expression

    idea

    Chooses between two values in one line, as in "warm" if temperature > 20 else "cold".

  • constructor

    idea

    The call that makes a new object, the class's name with parentheses, which runs the class's __init__ method to set the object up.

  • continue

    keyword

    Skips the rest of the current round of a loop and goes straight back to the loop's condition.

  • coordinates

    idea

    In pygame, (0, 0) is the top-left corner of the window, x grows to the right and y grows downward.

  • counting sort

    idea

    Sorts small whole numbers without comparing them, by counting how many times each value appears: O(n + k) for n values from 0 to k.

  • CSV

    idea

    A text file format where each line is one record and its fields are separated by a character such as a comma or a semicolon.

  • csv

    module

    Reads CSV files with csv.reader, which gives each line as a list of values and understands values in quotes.

D

E

F

  • f-string

    idea

    A string with f before its opening quote, in which each value in curly brackets is put into the text.

  • factorial

    idea

    The product of the whole numbers from 1 to n, written n!, a classic example of a recursive function.

  • False

    literal

    One of the two Boolean values, the value of a condition that doesn't hold; it is written with a capital F.

  • Fibonacci sequence

    idea

    The numbers 1, 1, 2, 3, 5, 8 and so on, where each number is the sum of the two before it; some start from 0, as 0, 1, 1, 2, 3.

  • file handle

    idea

    The variable through which a program reads or writes an open file, such as file in with open("notes.txt") as file:.

  • file mode

    idea

    The second argument of open, which says what the program does with the file, such as "w" to write a new file or "a" to add to its end.

  • file.read

    method

    Reads everything that's left in an open file and returns it as one string, line breaks included.

  • file.write

    method

    Writes a string into a file opened for writing or appending, adding no line break of its own.

  • FileNotFoundError

    exception

    Raised when a program tries to open a file that doesn't exist.

  • filter

    function

    Gives, as an iterator, the items of a series for which a function returns True.

  • filtering

    idea

    Keeping only the items that meet a condition, as an if at the end of a comprehension does.

  • float

    type

    The type of numbers with a decimal point, such as 2.5; float(...) turns a string such as "2.5" into a float.

  • for

    keyword

    Starts a loop that goes through the items of a list, the characters of a string or the numbers of a range, one at a time.

  • format specifier

    idea

    The part after a colon inside an f-string's braces that sets how a value is shown, such as {price:.2f} for two decimals or {name:<10} for a width.

  • Fraction

    type

    A class of the fractions module for exact fractions, such as Fraction(3, 4), with the attributes numerator and denominator.

  • fractions

    module

    The module with the class Fraction, for fractions that are exact where floating point numbers can be slightly off.

  • frame

    idea

    One picture that a pygame window shows when the program calls pygame.display.flip(); an animation is many frames that each differ a little.

  • from

    keyword

    Imports chosen names from a module straight into the program, as in from math import sqrt, so they work without the module's name in front.

  • function call

    idea

    Running a function by writing its name with parentheses after it, with the arguments, if any, inside them.

  • functional programming

    idea

    A style of programming that builds a program from functions that return new values, instead of changing variables step by step.

  • functools

    module

    A module of tools for working with functions, such as reduce, cache and lru_cache.

  • functools.cache

    function

    A decorator that memoizes a function: with @cache above its def, every result is kept by its arguments, which must be hashable.

  • functools.lru_cache

    function

    A decorator that remembers a function's results for the arguments it was called with, keeping at most maxsize of them and pushing out the least recently used.

  • functools.reduce

    function

    Combines the items of a series into one value by calling a function with the result so far and each item in turn.

G

  • game map

    idea

    A game's level kept as data, such as a list of strings with one character per square, which the program reads as level[y][x] and draws tile by tile.

  • game phase

    idea

    Which part of a game is going on, such as playing or game over, kept in an attribute that the main loop and the drawing check.

  • generator

    idea

    An object that produces the values of a series one at a time, only when they are asked for, made by a generator function or a generator expression.

  • generator expression

    idea

    A comprehension in round brackets, such as (n * n for n in numbers), which makes a generator instead of a list.

  • __getitem__

    method

    The method Python calls for m[key], as it calls __setitem__, __delitem__, __contains__ and __len__ for storing, del, in and len.

  • getter

    idea

    A method that gives the value of an attribute, in Python usually written with @property.

  • global

    keyword

    global name at the start of a function makes name mean the global variable, so the function can assign a new value to it.

  • global variable

    idea

    A variable made in the main program, outside every function, which a function can read but should get as a parameter instead.

  • graph

    idea

    A set of vertices (the things) and edges (the links between pairs of them); edges can go one way only, and they can have weights.

  • greedy algorithm

    idea

    Takes the choice that looks best right now and never goes back: right for fitting the most meetings, but it can miss the best answer, as with the coins 1, 4 and 5 for 8.

  • grid coordinates

    idea

    A place counted in squares of a grid, column x and row y, which becomes a point in pixels when each is multiplied by the size of a square, as in (x * SIZE, y * SIZE).

H

I

  • if

    keyword

    Starts a conditional statement, which runs the indented block below it only when its condition is true.

  • immutable

    idea

    An immutable value, such as a number, a string or a tuple, can't change after it's made, so operations on it make a new value instead.

  • import

    keyword

    Loads a module so that the program can use the functions and values in it, as in import math.

  • in

    keyword

    Checks whether one string is part of another, so part in text is True when text contains part.

  • indentation

    idea

    The spaces at the start of a line, which tell Python which lines belong to a block; four spaces is the standard.

  • IndentationError

    exception

    Python stops with it before running anything when a line's indentation doesn't fit, such as an unindented line after a colon.

  • index

    idea

    The number that tells where a character is in a string, counting from 0 for the first character.

  • IndexError

    exception

    The error Python stops with when an index is outside the indexes that a string has.

  • infinite loop

    idea

    A loop that never ends because no break can ever run, for example when the value it checks never changes.

  • inheritance

    idea

    A class taking over the attributes and methods of another class, as in class Wizard(Character):, so that shared code is written only once.

  • __init__

    method

    The constructor method of a class, which Python calls to set up each new object, with the object as self.

  • initialization

    idea

    Giving a variable its first value before a loop, so that the loop's condition can use it in the first round.

  • input

    function

    Shows its prompt, waits for the user to type a line and gives that line as a string.

  • input validation

    idea

    Checking that a value a program gets, such as typed input, makes sense before the program uses it.

  • insertion sort

    idea

    Sorts a list by taking the items one at a time and sliding each one left past the bigger ones: O(n²) in general, but O(n) on a nearly sorted list.

  • instance

    idea

    An object made from a class; Fraction(1, 2) is an instance of the class Fraction.

  • instance variable

    idea

    An attribute that each object has for itself, created with self. in a method such as __init__.

  • int

    type

    The type of whole numbers, such as -15 and 2026; int(...) turns a string of digits or a float into an integer.

  • interactive interpreter

    tool

    Python's line by line mode, started with python3 in a terminal, which runs each line as soon as you type it after the >>> prompt and shows its value.

  • interval

    idea

    A pair (start, end) such as a meeting. Sorted by start, the intervals that overlap merge in one pass; sorted by end, a greedy pass fits the most.

  • inversion

    idea

    A pair of items in the wrong order, a bigger one before a smaller one; insertion sort makes one move for each, and merge sort can count them in O(n log n).

  • is

    operator

    Checks whether two names refer to the very same object, while == checks whether two values are equal.

  • is not

    operator

    The opposite of is, true when two names refer to different objects, as in if result is not None:.

  • isinstance

    function

    Tells whether a value is an object of a class or of a class derived from it, as in isinstance(spark, Car).

  • __iter__

    method

    Runs when a for loop starts going through an object, and returns the iterator that hands out the items, often the object itself.

  • iterable

    idea

    A value that a for loop can go through, such as a list, a string, or an object of a class with the methods __iter__ and __next__.

  • iteration

    idea

    One run through the block of a loop, after which Python goes back to the start of the loop for the next one.

  • iterative

    idea

    Describes a solution that repeats with a loop, as opposed to a recursive one.

  • iterator

    idea

    An object that gives the values of a series one at a time and is used up after one pass, like the results of map, filter and generators.

  • itertools.accumulate

    function

    Gives the running totals of a list, so list(accumulate([5, 2, 7], initial=0)) is [0, 5, 7, 14], the prefix sums.

  • itertools.permutations

    function

    Gives every ordering of the items as tuples, such as ('a', 'b') and ('b', 'a'); n items give n! of them.

J

  • json

    module

    Turns JSON text into Python lists and dictionaries with json.loads, or json.load for an open file.

K

L

M

  • magic number

    idea

    A number in code whose meaning the reader has to know or guess, such as 3 for a box; a name or a character that looks like what it means is clearer.

  • main block

    idea

    The code under if __name__ == "__main__": at the end of a file, which runs when you run the file but not when a check loads it to call your functions.

  • main loop

    idea

    The while True loop of a game, which in every round handles the events, updates the game's state, draws the picture and shows it as a frame.

  • map

    function

    Calls a function on every item of a series and gives the results as an iterator, so list(map(int, texts)) makes a list of numbers.

  • Match.group

    method

    Gives the text that a regular expression matched, from the match object that re.search or re.fullmatch returns.

  • math

    module

    Mathematical functions and values, such as math.sqrt, math.floor, math.ceil, math.pi and math.inf, a float bigger than every finite number.

  • math.ceil

    function

    Rounds a number up to a whole number, so math.ceil(2.1) is 3, which is handy when leftovers still need a place of their own.

  • math.sin

    function

    Gives the sine of an angle in radians; with math.cos, it gives the point at that angle on a circle.

  • matrix

    idea

    A table of values with rows and columns, kept as a list of rows, so grid[row][column] is one value.

  • max

    function

    Returns the greatest item of a list, and min returns the smallest.

  • memoization

    idea

    Storing each answer of a function in a dict, a memo, by its arguments, so that a repeated call looks the answer up instead of working it out again.

  • merge sort

    idea

    Sorts by splitting the list in halves, sorting each half the same way and merging the two sorted halves, in O(n log n) time with O(n) extra memory.

  • method

    idea

    A function that belongs to a value and is called after it with a dot, as in text.find("a").

  • module

    idea

    A file of Python code whose functions and values other programs can import, either from the standard library or written by you.

  • ModuleNotFoundError

    exception

    Raised when an import names a module that Python can't find, such as a file that doesn't exist.

  • monotonic stack

    idea

    A stack whose items stay in order from bottom to top, which finds the next greater value for every item of a list in O(n).

  • mutable

    idea

    A mutable value, such as a list or a dictionary, can change after it's made, and every variable that refers to it sees the change.

  • mutable default value

    idea

    A list or dictionary as a parameter's default value is created only once and shared by every call, so use None and create it in the method.

N

O

P

  • palindrome

    idea

    A string that reads the same backwards and forwards, such as "racecar".

  • parameter

    idea

    A variable named in a function's header, which gets its value from the matching argument of each call.

  • PascalCase

    idea

    The style for class names, with every word starting with a capital letter and no underscores, as in BankAccount.

  • pass

    keyword

    A statement that does nothing, used where Python needs one, such as the body of a function not written yet.

  • prefix sum

    idea

    A list whose item i is the sum of the first i values, so the sum of any stretch values[a:b] is prefix[b] - prefix[a], in O(1).

  • private attribute

    idea

    An attribute whose name starts with two underscores, such as self.__balance, which only the class's own methods use by that name.

  • private method

    idea

    A helper method whose name starts with two underscores, which the class's own methods call with self. and the client can't call.

  • @property

    function

    A decorator that turns a method into a getter, so the client reads the value like an attribute, without parentheses.

  • protected attribute

    idea

    An attribute whose name starts with one underscore, such as self._songs, which by agreement is for the class and its derived classes but not for clients.

  • pruning

    idea

    Stopping a branch of a search as soon as it can't lead to an answer, such as a queen on an attacked square, so whole subtrees of choices are never tried.

  • pure function

    idea

    A function whose only result is the value it returns, so it changes none of its arguments and nothing else.

  • pygame

    module

    A library for writing games and other programs with graphics, installed with pip install pygame-ce and taken into use with import pygame.

  • pygame.display.flip

    function

    Shows everything drawn in the window so far as one new frame.

  • pygame.display.set_caption

    function

    Sets the title in the window's title bar.

  • pygame.display.set_mode

    function

    Opens a window of the given size, as in set_mode((320, 240)), and returns it as a surface to draw on.

  • pygame.draw

    module

    Draws shapes on a surface with functions such as rect, circle, line and polygon, which take the surface and the color first.

  • pygame.event.get

    function

    Returns a list of the events that have happened since it was last called, such as key presses, mouse clicks and closing the window.

  • pygame.font.SysFont

    function

    Makes a font of a named typeface and size, whose render method makes an image of a text to draw with blit.

  • pygame.image.load

    function

    Reads an image file, such as a PNG, and returns it as a surface that can be drawn with blit.

  • pygame.key.get_pressed

    function

    Tells which keys are held down right now: keys[pygame.K_LEFT] is True while the left arrow is down.

  • pygame.Rect

    type

    A rectangle with a position and a size, with attributes such as right and center that follow when it moves.

  • pygame.time.Clock

    type

    A clock whose tick(60), called once in every round of the main loop, keeps the loop from going round more than 60 times a second.

  • pygame.time.get_ticks

    function

    Gives the number of milliseconds since the program called pygame.init().

  • pygame.transform.rotate

    function

    Returns a new image, the given one turned counterclockwise by a number of degrees, made bigger so that its corners fit.

Q

  • quantifier

    idea

    A mark after part of a regular expression, such as *, +, ? or {3}, that says how many times that part repeats.

  • quickselect

    idea

    Finds the k-th smallest value without sorting, by partitioning around a pivot as quicksort does and going on only in the side that holds it: O(n) on average, O(n²) at worst.

  • quicksort

    idea

    Sorts by moving the items smaller than a pivot before it and the rest after it, then sorting both sides: O(n log n) on average, O(n²) with bad pivots.

R

S

T

  • test level

    idea

    A small, easy level made only for testing one part of a game, such as its ending, without playing the whole game every time.

  • tile

    idea

    A small square picture; tiles drawn side by side in a grid make up a game's map.

  • timedelta

    type

    A length of time, such as the difference of two datetimes, with the attributes days and seconds; adding one to a datetime moves it.

  • topological sort

    idea

    Orders the vertices of a directed graph so that every edge points forward, as for jobs that wait for others; Kahn's algorithm finds one, or shows there is a cycle.

  • tree traversal

    idea

    Visiting every node of a tree once: pre-order puts each node before its subtrees, in-order between them (sorted, in a BST) and post-order after them.

  • trie

    idea

    A tree that stores words letter by letter, so that words with the same beginning share nodes, and finding a word or a prefix of m letters takes O(m).

  • True

    literal

    One of the two Boolean values, the value of a condition that holds; it is written with a capital T.

  • try

    keyword

    Starts a block of code that might raise an exception, which the except blocks after it can handle.

  • tuple

    type

    An ordered group of values, such as (3, 7), that you can index and loop over like a list but can't change after it's made.

  • two pointers

    idea

    Two indexes that walk along sorted data, each in one direction only, where the order tells which one to move next, so the whole walk is O(n).

  • type

    function

    Tells the type of a value, such as int, float, str or bool.

  • type hint

    idea

    A note in a function's first line that tells the types of its parameters and its return value, as in def area(width: float) -> float:, which Python doesn't check.

  • TypeError

    exception

    Python stops with it when an operation gets a value of a type it can't work with, such as a string plus a number.

U

  • UnboundLocalError

    exception

    Raised when a function reads a local variable before giving it a value, often because it assigns to a global name without global.

  • union-find

    idea

    Keeps groups that only ever merge as trees in a list of parents; with union by size and path compression, joining two groups and asking if two items share one take almost O(1).

  • unpacking

    idea

    Putting the values of a tuple into several variables at once, as in minutes, seconds = to_minutes(135).

  • user interface

    idea

    The part of a program that talks to the user, such as a text interface that reads commands and calls the logic's methods.

V

W

Y

  • yield

    keyword

    Hands out one value from a generator function and pauses it there, so that it can continue from the same spot when the next value is asked for.

Z

  • zip

    function

    Goes through two or more lists side by side, giving tuples of the items at the same place, as in for w, v in zip(weights, values):.