Comprehensive Python Cheatsheet
Download text file, Buy PDF, Fork me on GitHub or Check out FAQ.

Contents
1. Collections: List
, Dictionary
, Set
, Tuple
, Range
, Enumerate
, Iterator
, Generator
.
2. Types: Type
, String
, Regular_Exp
, Format
, Numbers
, Combinatorics
, Datetime
.
3. Syntax: Args
, Inline
, Closure
, Decorator
, Class
, Duck_Type
, Enum
, Exception
.
4. System: Exit
, Print
, Input
, Command_Line_Arguments
, Open
, Path
, OS_Commands
.
5. Data: JSON
, Pickle
, CSV
, SQLite
, Bytes
, Struct
, Array
, Memory_View
, Deque
.
6. Advanced: Threading
, Operator
, Introspection
, Metaprograming
, Eval
, Coroutines
.
7. Libraries: Progress_Bar
, Plot
, Table
, Curses
, Logging
, Scraping
, Web
, Profile
,
NumPy
, Image
, Audio
, Pygame
.
Main
List
- Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
Dictionary
Counter
Set
Frozen Set
- Is immutable and hashable.
- That means it can be used as a key in a dictionary or as an element in a set.
Tuple
Tuple is an immutable and hashable list.
Named Tuple
Tuple's subclass with named elements.
Range
Enumerate
Iterator
Itertools
Generator
- Any function that contains a yield statement returns a generator.
- Generators and iterators are interchangeable.
Type
- Everything is an object.
- Every object has a type.
- Type and class are synonymous.
Some types do not have built-in names, so they must be imported:
Abstract Base Classes
Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not.
String
- Also:
'lstrip()'
,'rstrip()'
. - Also:
'lower()'
,'upper()'
,'capitalize()'
and'title()'
.
Property Methods
- Also:
'isspace()'
checks for'[ \t\n\r\f\v…]'
.
Regex
- Search() and match() return None if they can't find a match.
- Argument
'flags=re.IGNORECASE'
can be used with all functions. - Argument
'flags=re.MULTILINE'
makes'^'
and'$'
match the start/end of each line. - Argument
'flags=re.DOTALL'
makes dot also accept the'\n'
. - Use
r'\1'
or'\\1'
for backreference. - Add
'?'
after an operator to make it non-greedy.
Match Object
Special Sequences
- By default digits, alphanumerics and whitespaces from all alphabets are matched, unless
'flags=re.ASCII'
argument is used. - Use a capital letter for negation.
Format
Attributes
General Options
Strings
'!r'
calls object's repr() method, instead of str(), to get a string.
Numbers
Floats
Comparison of presentation types:
Ints
Numbers
Types
'int(<str>)'
and'float(<str>)'
raise ValueError on malformed strings.- Decimal numbers can be represented exactly, unlike floats where
'1.1 + 2.2 != 3.3'
. - Precision of decimal operations is set with:
'decimal.getcontext().prec = <int>'
.
Basic Functions
Math
Statistics
Random
Bin, Hex
Bitwise Operators
Combinatorics
- Every function returns an iterator.
- If you want to print the iterator, you need to pass it to the list() function first!
Datetime
- Module 'datetime' provides 'date'
<D>
, 'time'<T>
, 'datetime'<DT>
and 'timedelta'<TD>
classes. All are immutable and hashable. - Time and datetime objects can be 'aware'
<a>
, meaning they have defined timezone, or 'naive'<n>
, meaning they don't. - If object is naive, it is presumed to be in the system's timezone.
Constructors
- Use
'<D/DT>.weekday()'
to get the day of the week (Mon == 0). 'fold=1'
means the second pass in case of time jumping back for one hour.'<DTa> = resolve_imaginary(<DTa>)'
fixes DTs that fall into the missing hour.
Now
- To extract time use
'<DTn>.time()'
,'<DTa>.time()'
or'<DTa>.timetz()'
.
Timezone
Encode
- ISO strings come in following forms:
'YYYY-MM-DD'
,'HH:MM:SS.ffffff[±<offset>]'
, or both separated by an arbitrary character. Offset is formatted as:'HH:MM'
. - Epoch on Unix systems is:
'1970-01-01 00:00 UTC'
,'1970-01-01 01:00 CET'
, ...
Decode
Format
- When parsing,
'%z'
also accepts'±HH:MM'
. - For abbreviated weekday and month use
'%a'
and'%b'
.
Arithmetics
Arguments
Inside Function Call
Inside Function Definition
Splat Operator
Inside Function Call
Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.
Is the same as:
Inside Function Definition
Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.
Legal argument combinations:
Other Uses
Inline
Lambda
Comprehension
Is the same as:
Map, Filter, Reduce
Any, All
If - Else
Namedtuple, Enum, Dataclass
Closure
We have a closure in Python when:
- A nested function references a value of its enclosing function and then
- the enclosing function returns the nested function.
- If multiple nested functions within enclosing function reference the same value, that value gets shared.
- To dynamically access function's first free variable use
'<function>.__closure__[0].cell_contents'
.
Partial
- Partial is also useful in cases when function needs to be passed as an argument, because it enables us to set its arguments beforehand.
- A few examples being:
'defaultdict(<function>)'
,'iter(<function>, to_exclusive)'
and dataclass's'field(default_factory=<function>)'
.
Non-Local
If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.
Decorator
A decorator takes a function, adds some functionality and returns it.
Debugger Example
Decorator that prints function's name every time it gets called.
- Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).
- Without it
'add.__name__'
would return'out'
.
LRU Cache
Decorator that caches function's return values. All function's arguments must be hashable.
- CPython interpreter limits recursion depth to 1000 by default. To increase it use
'sys.setrecursionlimit(<depth>)'
.
Parametrized Decorator
A decorator that accepts arguments and returns a normal decorator that accepts a function.
Class
- Return value of repr() should be unambiguous and of str() readable.
- If only repr() is defined, it will also be used for str().
Str() use cases:
Repr() use cases:
Constructor Overloading
Inheritance
Multiple Inheritance
MRO determines the order in which parent classes are traversed when searching for a method:
Property
Pythonic way of implementing getters and setters.
Dataclass
Decorator that automatically generates init(), repr() and eq() special methods.
- Objects can be made sortable with
'order=True'
and/or immutable and hashable with'frozen=True'
. - Function field() is needed because
'<attr_name>: list = []'
would make a list that is shared among all instances. - Default_factory can be any callable.
Inline:
Slots
Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.
Copy
Duck Types
A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.
Comparable
- If eq() method is not overridden, it returns
'id(self) == id(other)'
, which is the same as'self is other'
. - That means all objects compare not equal by default.
- Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.
Hashable
- Hashable object needs both hash() and eq() methods and its hash value should never change.
- Hashable objects that compare equal must have the same hash value, meaning default hash() that returns
'id(self)'
will not do. - That is why Python automatically makes classes unhashable if you only implement eq().
Sortable
- With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.
Iterator
- Any object that has methods next() and iter() is an iterator.
- Next() should return next item or raise StopIteration.
- Iter() should return 'self'.
Python has many different iterator objects:
- Iterators returned by the iter() function, such as list_iterator and set_iterator.
- Objects returned by the itertools module, such as count, repeat and cycle.
- Generators returned by the generator functions and generator expressions.
- File objects returned by the open() function, etc.
Callable
- All functions and classes have a call() method, hence are callable.
- When this cheatsheet uses
'<function>'
as an argument, it actually means'<callable>'
.
Context Manager
- Enter() should lock the resources and optionally return an object.
- Exit() should release the resources.
- Any exception that happens inside the with block is passed to the exit() method.
- If it wishes to suppress the exception it must return a true value.
Iterable Duck Types
Iterable
- Only required method is iter(). It should return an iterator of object's items.
- Contains() automatically works on any object that has iter() defined.
Collection
- Only required methods are iter() and len().
- This cheatsheet actually means
'<iterable>'
when it uses'<collection>'
. - I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.
Sequence
- Only required methods are len() and getitem().
- Getitem() should return an item at index or raise IndexError.
- Iter() and contains() automatically work on any object that has getitem() defined.
- Reversed() automatically works on any object that has getitem() and len() defined.
ABC Sequence
- It's a richer interface than the basic sequence.
- Extending it generates iter(), contains(), reversed(), index() and count().
- Unlike
'abc.Iterable'
and'abc.Collection'
, it is not a duck type. That is why'issubclass(MySequence, abc.Sequence)'
would return False even if MySequence had all the methods defined.
Table of required and automatically available special methods:
- Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.
- Names of their required methods are stored in
'<abc>.__abstractmethods__'
.
Enum
- If there are no numeric values before auto(), it returns 1.
- Otherwise it returns an increment of the last numeric value.
Inline
User-defined functions cannot be values, so they must be wrapped:
- Another solution in this particular case is to use built-in functions and_() and or_() from the module operator.
Exceptions
Basic Example
Complex Example
Catching Exceptions
- Also catches subclasses of the exception.
- Use
'traceback.print_exc()'
to print the error message to stderr.
Raising Exceptions
Re-raising caught exception:
Exception Object
Built-in Exceptions
Collections and their exceptions:
Useful built-in exceptions:
User-defined Exceptions
Exit
Exits the interpreter by raising SystemExit exception.
- Use
'file=sys.stderr'
for messages about errors. - Use
'flush=True'
to forcibly flush the stream.
Pretty Print
- Levels deeper than 'depth' get replaced by '...'.
Input
Reads a line from user input or pipe if present.
- Trailing newline gets stripped.
- Prompt string is printed to the standard output before reading input.
- Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.
Command Line Arguments
Argument Parser
- Use
'help=<str>'
to set argument description. - Use
'default=<el>'
to set the default value. - Use
'type=FileType(<mode>)'
for files.
Open
Opens the file and returns a corresponding file object.
'encoding=None'
means that the default encoding is used, which is platform dependent. Best practice is to use'encoding="utf-8"'
whenever possible.'newline=None'
means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.'newline=""'
means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.
Modes
'r'
- Read (default).'w'
- Write (truncate).'x'
- Write or fail if the file already exists.'a'
- Append.'w+'
- Read and write (truncate).'r+'
- Read and write from the start.'a+'
- Read and write from the end.'t'
- Text mode (default).'b'
- Binary mode.
Exceptions
'FileNotFoundError'
can be raised when reading with'r'
or'r+'
.'FileExistsError'
can be raised when writing with'x'
.'IsADirectoryError'
and'PermissionError'
can be raised by any.'OSError'
is the parent class of all listed exceptions.
File Object
- Methods do not add or strip trailing newlines, even writelines().
Read Text from File
Write Text to File
Path
DirEntry
Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.
Path Object
OS Commands
Files and Directories
- Paths can be either strings, Paths or DirEntry objects.
- Functions report OS related errors by raising either OSError or one of its subclasses.
Shell Commands
Sends '1 + 1' to the basic calculator and captures its output:
Sends test.in to the basic calculator running in standard mode and saves its output to test.out:
JSON
Text file format for storing collections of strings and numbers.
Read Object from JSON File
Write Object to JSON File
Pickle
Binary file format for storing objects.
Read Object from File
Write Object to File
CSV
Text file format for storing spreadsheets.
Read
- File must be opened with
'newline=""'
argument, or newlines embedded inside quoted fields will not be interpreted correctly!
Write
- File must be opened with
'newline=""'
argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!
Parameters
'dialect'
- Master parameter that sets the default values.'delimiter'
- A one-character string used to separate fields.'quotechar'
- Character for quoting fields that contain special characters.'doublequote'
- Whether quotechars inside fields get doubled or escaped.'skipinitialspace'
- Whether whitespace after delimiter gets stripped.'lineterminator'
- Specifies how writer terminates rows.'quoting'
- Controls the amount of quoting: 0 - as necessary, 1 - all.'escapechar'
- Character for escaping 'quotechar' if 'doublequote' is False.
Dialects
Read Rows from CSV File
Write Rows to CSV File
SQLite
Server-less database engine that stores each database into a separate file.
Connect
Opens a connection to the database file. Creates a new file if path doesn't exist.
Read
Returned values can be of type str, int, float, bytes or None.
Write
Or:
Placeholders
- Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
- Bools will be stored and returned as ints and dates as ISO formatted strings.
Example
In this example values are not actually saved because 'con.commit()'
is omitted!
MySQL
Has a very similar interface, with differences listed below.
Bytes
Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.
Encode
Decode
Read Bytes from File
Write Bytes to File
Struct
- Module that performs conversions between a sequence of numbers and a bytes object.
- Machine’s native type sizes and byte order are used by default.
Example
Format
For standard type sizes start format string with:
'='
- native byte order'<'
- little-endian'>'
- big-endian (also'!'
)
Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets:
'x'
- pad byte'b'
- char (1)'h'
- short (2)'i'
- int (4)'l'
- long (4)'q'
- long long (8)
Floating point types:
'f'
- float (4)'d'
- double (8)
Array
List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.
Memory View
- A sequence object that points to the memory of another object.
- Each element can reference a single or multiple consecutive bytes, depending on format.
- Order and number of elements can be changed with slicing.
Decode
Deque
A thread-safe list with efficient appends and pops from either side. Pronounced "deck".
Threading
- CPython interpreter can only run a single thread at a time.
- That is why using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.
Thread
- Use
'kwargs=<dict>'
to pass keyword arguments to the function. - Use
'daemon=True'
, or the program will not be able to exit while the thread is alive.
Lock
Or:
Semaphore, Event, Barrier
Thread Pool Executor
Future:
Queue
A thread-safe FIFO queue. For LIFO queue use LifoQueue.
Operator
Module of functions that provide the functionality of operators.
Introspection
Inspecting code at runtime.
Variables
Attributes
Parameters
Metaprograming
Code that generates code.
Type
Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.
Meta Class
A class that creates classes.
Or:
- New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.
- It receives the same arguments as init(), except for the first one that specifies the desired type of the returned instance (MyMetaClass in our case).
- Like in our case, new() can also be called directly, usually from a new() method of a child class (
def __new__(cls): return super().__new__(cls)
). - The only difference between the examples above is that my_meta_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.
Metaclass Attribute
Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().
Type Diagram
Inheritance Diagram
Eval
Coroutines
- Coroutines have a lot in common with threads, but unlike threads, they only give up control when they call another coroutine and they don’t use as much memory.
- Coroutine definition starts with
'async'
and its call with'await'
. 'asyncio.run(<coroutine>)'
is the main entry point for asynchronous programs.- Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.
- Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
Runs a terminal game where you control an asterisk that must avoid numbers:
Libraries
Progress Bar
Plot
Table
Prints a CSV file as an ASCII table:
Curses
Clears the terminal, prints a message and waits for the ESC key press:
Logging
- Levels:
'debug'
,'info'
,'success'
,'warning'
,'error'
,'critical'
.
Exceptions
Exception description, stack trace and values of variables are appended automatically.
Rotation
Argument that sets a condition when a new log file is created.
'<int>'
- Max file size in bytes.'<timedelta>'
- Max age of a file.'<time>'
- Time of day.'<str>'
- Any of above as a string:'100 MB'
,'1 month'
,'monday at 12:00'
, ...
Retention
Sets a condition which old log files get deleted.
'<int>'
- Max number of files.'<timedelta>'
- Max age of a file.'<str>'
- Max age as a string:'1 week, 3 days'
,'2 months'
, ...
Scraping
Scrapes Python's URL, version number and logo from Wikipedia page:
Web
Run
Static Request
Dynamic Request
REST Request
Test:
Profiling
Stopwatch
High performance:
Timing a Snippet
Profiling by Line
Call Graph
Generates a PNG image of a call graph with highlighted bottlenecks:
NumPy
Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code.
- Shape is a tuple of dimension sizes.
- Axis is the index of a dimension that gets collapsed. The leftmost dimension has index 0.
Indexing
- If row and column indexes differ in shape, they are combined with broadcasting.
Broadcasting
Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.
1. If array shapes differ in length, left-pad the shorter shape with ones:
2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
3. If neither non-matching dimension has size 1, raise an error.
Example
For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]
):
Image
Modes
'1'
- 1-bit pixels, black and white, stored with one pixel per byte.'L'
- 8-bit pixels, greyscale.'RGB'
- 3x8-bit pixels, true color.'RGBA'
- 4x8-bit pixels, true color with transparency mask.'HSV'
- 3x8-bit pixels, Hue, Saturation, Value color space.
Examples
Creates a PNG image of a rainbow gradient:
Adds noise to a PNG image:
Drawing
- Use
'fill=<color>'
to set the primary color. - Use
'outline=<color>'
to set the secondary color. - Color can be specified as a tuple, int,
'#rrggbb'
string or a color name.
Animation
Creates a GIF of a bouncing ball:
Audio
- Bytes object contains a sequence of frames, each consisting of one or more samples.
- In a stereo signal, the first sample of a frame belongs to the left channel.
- Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.
- If sample width is one, then the integer should be encoded unsigned.
- For all other sizes, the integer should be encoded signed with little-endian byte order.
Sample Values
Read Float Samples from WAV File
Write Float Samples to WAV File
Examples
Saves a sine wave to a mono WAV file:
Adds noise to a mono WAV file:
Plays a WAV file:
Text to Speech
Synthesizer
Plays Popcorn by Gershon Kingsley:
Pygame
Basic Example
Rectangle
Object for storing rectangular coordinates.
Surface
Object for representing images.