For details about sorted(), min() and max() see sortable.
Module operator provides functions itemgetter() and mul() that
offer the same functionality as lambda expressions above.
Insert new element to list at given index and move the rest to the right
Removes and returns item at index or from the end.
Don’t forget, indexing starts from 0.
Returns number of list occurrences. Also works on strings.
items = [0, 1, 0, 6, 0, 5, 6, 7, 0, 9]
Return index of the first value occurrence or raise ValueError.
items = [0, 1, 0, 6, 0, 5, 6, 7, 0, 9]
Remove first occurrence of the item or raises ValueError.
items = [0, 1, 0, 6, 0, 5, 6, 7, 0, 9]
Remove all items. Also works on dictionary and set.
Dictionary
Get keys from dict
Get values from dict
Get key-value tuples from dict
Get value from dict by key, return default value if key not in dict
Python dict, set key default value if key is not in dict
What is the syntax for creating a defaultdict in Python?
What this code do collections.defaultdict(lambda: 1) ?
Returns a dict with default value 1.
What this code do dict(zip(keys, values))
Creates a dict from two collections.
What this code do dict.fromkeys(keys, value) ?
Creates a dict from collection of keys with the same value.
What this code do <dict>.update(<dict>)?
Adds items. Replaces ones with matching keys.
What this code do <dict>.pop(<key>)?
Removes item or raises KeyError.
What this code do {k for k, v in <dict>.items() if v == value}?
Returns set of keys that point to the value.
What this code do {k: v for k, v in <dict>.items() if k in keys}?
Returns a dictionary, filtered by keys.
Counter
What print values are?
Set
How initialize set (2 ways)?
How create empty set?
Is these sets are the same?
No, first is set of chars, second is set of string.
How add items to set() (2 ways)?
How update sets (2 ways)?
How union 2 sets, what difference between set update?
How do intersection of 2 sets?
How do difference of 2 sets?
How do symmetric_difference of 2 sets?
Return a new set with elements in either the set or other but not both.
How do issubset (2 ways)?
How do issuperset (2 ways)?
How remove item from set (3 ways)?
Frozen Set
Frozen set is an immutable and hashable set.
That means it can be used as a key in a dictionary or as an element in a set.
How to use them as a key in a dictionary or as an element in a set?
Tuple
Tuple is an immutable and hashable list.
How to create empty tuple or tuple with elements?
Named Tuple
Named tuple is tuple’s subclass with?
named elements
Range
Immutable and hashable sequence of integers.
Output of this block of code?
[0, 1, 2]
[0, 2] # because 0 then 0+2=2 then 2+2=4, but it's not in range
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # end of range is -1
Enumerate
Output of this block of code?
0 one
1 two
2 three
Iterator
How to create iterator from collection or function?
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. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().
String
Also: 'lstrip()', 'rstrip()' and 'rsplit()'.
Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.
Property Methods
'isspace()' checks for whitespaces: '[ \t\n\r\f\v\x1c-\x1f\x85\xa0\u1680…]'.
Regex
Argument ‘new’ can be a function that accepts a Match object and returns a string.
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 '.' also accept the '\n'.
Use r'\1' or '\\1' for backreference ('\1' returns a character with octal code 1).
Add '?' after '*' and '+' to make them non-greedy.
Match Object
Special Sequences
By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
Format
Attributes
General Options
Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
Adding '!r' before the colon converts object to string by calling its repr() method.
Strings
Numbers
Floats
Comparison of presentation types:
When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
Ints
Numbers
'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
Decimal numbers are stored exactly, unlike most floats where '1.1 + 2.2 != 3.3'.
Floats can be compared with: 'math.isclose(<float>, <float>)'.
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 as an int, with Monday being 0.
'fold=1' means the second pass in case of time jumping back for one hour.
Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
'<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.mmmuuu[±HH:MM]', or both separated by an arbitrary character. All parts following the hours are optional.
Format code '%z' accepts '±HH[:]MM' and returns '±HHMM' (or '' if datetime is naive).
For abbreviated weekday and month use '%a' and '%b'.
Arithmetics
Arguments
Inside Function Call
Inside Function Definition
Default values are evaluated when function is first encountered in the scope.
Any mutation of a mutable default value will persist between invocations!
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
Comprehensions
Map, Filter, Reduce
Any, All
Conditional Expression
Named Tuple, Enum, Dataclass
Package is a collection of modules, but it can also define its own objects.
On a filesystem this corresponds to a directory of Python files with an optional init script.
Running 'import <package>' does not automatically provide access to the package’s modules unless they are explicitly imported in its init script.
Closure
We have/get 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.
It can be any callable, but is usually implemented as a function that returns a closure.
Debugger Example
Decorator that prints function’s name every time the function is 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.
Default size of the cache is 128 values. Passing 'maxsize=None' makes it unbounded.
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.
Using only '@debug' to decorate the add() function would not work here, because debug would then receive the add() function as a ‘print_result’ argument. Decorators can however manually check if the argument they received is a function and act accordingly.
Class
Return value of repr() should be unambiguous and of str() readable.
If only repr() is defined, it will also be used for str().
Methods decorated with '@staticmethod' do not receive ‘self’ nor ‘cls’ as their first arg.
Expressions that call the str() method:
Expressions that call the repr() method:
Constructor Overloading
Inheritance
Multiple Inheritance
MRO determines the order in which parent classes are traversed when searching for a method or an attribute:
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 immutable with 'frozen=True'.
For object to be hashable, all attributes must be hashable and ‘frozen’ must be True.
Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances. Its ‘default_factory’ argument can be any callable.
For attributes of arbitrary type use 'typing.Any'.
Inline:
Rest of type annotations (CPython interpreter ignores them all):
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. False is returned if both return NotImplemented.
Ne() automatically works on any object that has eq() defined.
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 and the rest will be automatically generated.
Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn’t arise in other contexts.
When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.
Characters are compared by their Unicode IDs. Use module ‘locale’ for proper alphabetical order.
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:
Sequence 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.
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
With statements only work with objects that have enter() and exit() special methods.
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.
The exit() method can suppress the exception by returning 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(). Len() should return the number of items.
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’. The only drawback of this decision is that a reader could think a certain function doesn’t accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.
Sequence
Only required methods are getitem() and len().
Getitem() should return an item at the passed 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.
Discrepancies between glossary definitions and abstract base classes:
Glossary defines iterable as any object with iter() or getitem() and sequence as any object with getitem() and len(). It does not define collection.
Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len().
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. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, because they are registered as its virtual subclasses.
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
Function auto() returns an increment of the last numeric value or 1.
Accessing a member named after a reserved keyword causes SyntaxError.
Methods receive the member they were called on as the ‘self’ argument.
Inline
User-defined functions cannot be values, so they must be wrapped:
Exceptions
Complex Example
Code inside the 'else' block will only be executed if 'try' block had no exceptions.
Code inside the 'finally' block will always be executed (unless a signal is received).
All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try/except clause (only function blocks delimit scope).
To catch signals use 'signal.signal(signal_number, <func>)'.
Catching Exceptions
Also catches subclasses of the exception.
Use 'traceback.print_exc()' to print the error message to stderr.
Use 'print(<name>)' to print just the cause of the exception (its arguments).
Use 'logging.exception(<message>)' to log the passed message, followed by the full error message of the caught exception.
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.
Print
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 the 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/ctrl-z⏎) or input stream gets exhausted.
Command Line Arguments
Argument Parser
Use 'help=<str>' to set argument description that will be displayed in help message.
Use 'default=<el>' to set the default value.
Use 'type=FileType(<mode>)' for files. Accepts ‘encoding’, but ‘newline’ is None.
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 every ‘\n’, ‘\r’ and ‘\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 ('br', 'bw', 'bx', …).
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
Paths
DirEntry
Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.
Path Object
OS Commands
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 Python objects.
Read Object from File
Write Object to File
CSV
Text file format for storing spreadsheets.
Read
File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
To print the spreadsheet to the console use Tabulate library.
For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
Reader accepts any iterator of strings, not just files.
Write
File must be opened with a '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. String or a ‘csv.Dialect’ object.
'delimiter' - A one-character string used to separate fields.
'quotechar' - Character for quoting fields that contain special characters.
'doublequote' - Whether quotechars inside fields are/get doubled or escaped.
'skipinitialspace' - Is space character at the start of the field stripped by the reader.
'lineterminator' - How writer terminates rows. Reader is hardcoded to ‘\n’, ‘\r’, ‘\r\n’.
'quoting' - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.
'escapechar' - Character for escaping quotechars if doublequote is False.
Dialects
Read Rows from CSV File
Write Rows to CSV File
SQLite
A server-less database engine that stores each database into a separate file.
Read
Write
Or:
Placeholders
Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
Values are not actually saved in this example because 'conn.commit()' is omitted!
SqlAlchemy
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.
System’s type sizes, byte order, and alignment rules are used by default.
Format
For standard type sizes and manual alignment (padding) start format string with:
'=' - System’s byte order (usually little-endian).
'<' - Little-endian.
'>' - Big-endian (also '!').
Besides numbers, pack() and unpack() also support bytes objects as part of the sequence:
'c' - A bytes object with a single element. For pad byte use 'x'.
'<n>s' - A bytes object with n elements.
Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:
'b' - char (1/1)
'h' - short (2/2)
'i' - int (2/4)
'l' - long (4/4)
'q' - long long (8/8)
Floating point types:
'f' - float (4/4)
'd' - double (8/8)
Array
List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Sizes and byte order are always determined by the system, however bytes of each element can be swapped with byteswap() method.
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.
Casting only works between char and other types and uses system’s sizes.
Byte order is always determined by the system.
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
Object that manages thread execution.
An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable.
Queue
A thread-safe FIFO queue. For LIFO queue use LifoQueue.
Operator
Module of functions that provide the functionality of operators.
Binary operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.
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() start multiple coroutines at the same time.
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
Runs a basic file explorer in the terminal:
Logging
Setup
Parent logger can be specified by naming the child logger '<parent>.<name>'.
Formatter also supports: pathname, filename, funcName, lineno, thread and process.
A 'handlers.RotatingFileHandler' creates and deletes log files based on ‘maxBytes’ and ‘backupCount’ arguments.
Creates a logger that writes all messages to a file and sends them to the root logger that prints to stdout:
Scraping
Scrapes Python’s URL, version number and logo from its Wikipedia page:
Web
Flask is a micro web framework/server. If you just want to open a html file in a web browser use 'webbrowser.open(<path>)' instead.
Starts the app at 'http://localhost:5000'. Use 'host="0.0.0.0"' to run externally.
Install a WSGI server like Waitress and a HTTP server such as Nginx for better security.
Debug mode restarts the app whenever script changes and displays errors in the browser.
Static Request
Dynamic Request
To return an error code use 'abort(<int>)' and to redirect use 'redirect(<url>)'.
'request.args[<str>]' returns parameter from the query string (URL part after ’?’).
Use 'session[key] = value' to store session data like username, etc.
REST Request
Starts the app in its own thread and queries it with a post request:
Profiling
Timing a Snippet
Profiling by Line
Call Graph
Generates a PNG image of the call graph with highlighted bottlenecks:
NumPy
Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code. An even faster alternative that runs on a GPU is called CuPy.
Shape is a tuple of dimension sizes. A 100x50 RGB image has shape (50, 100, 3).
Axis is an index of the dimension that gets aggregated. Leftmost dimension has index 0. Summing the RGB image along axis 2 will return a greyscale image with shape (50, 100).
Indexing
Indexes should not be tuples because Python converts 'obj[i, j]' to 'obj[(i, j)]'!
Any value that is broadcastable to the indexed shape can be assigned to the selection.
Broadcasting
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:
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:
Image Draw
Use 'fill=<color>' to set the primary color.
Use 'width=<int>' to set the width of lines or contours.
Use 'outline=<color>' to set the color of the contours.
Color can be an int, tuple, '#rrggbb[aa]' 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 byte, 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 440 Hz 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
Rectangle
Object for storing rectangular coordinates.
Surface
Object for representing images.
Font
Sound
Basic Mario Brothers Example
Pandas
Series
Ordered dictionary with a name.
Series — Aggregate, Transform, Map:
Keys/indexes/bools can’t be tuples because 'obj[x, y]' is converted to 'obj[(x, y)]'!
Methods ffill(), interpolate(), fillna() and dropna() accept 'inplace=True'.
Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
DataFrame
Table with labeled rows and columns.
DataFrame — Merge, Join, Concat:
DataFrame — Aggregate, Transform, Map:
All operations operate on columns by default. Pass 'axis=1' to process the rows instead.
Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result’s values.
DataFrame — Plot, Encode, Decode:
GroupBy
Object that groups together rows of a dataframe based on the value of the passed column.
GroupBy — Aggregate, Transform, Map:
Rolling
Object for rolling window calculations.
Plotly
Displays a line chart of total coronavirus deaths per million grouped by continent:
Displays a multi-axis line chart of total coronavirus cases and changes in prices of Bitcoin, Dow Jones and gold:
PySimpleGUI
Appendix
Cython
Library that compiles Python code into C.
Definitions:
All 'cdef' definitions are optional, but they contribute to the speed-up.
Script needs to be saved with a 'pyx' extension.
PyInstaller
File paths need to be updated to 'os.path.join(sys._MEIPASS, <path>)'.