Skip to content

Python3 Cheat Sheet

Built-in Methods

abs(num) Get absolute value
all(iterable) Return True if all elements in the iterable are True
any(iterable) Return True if any element in the iterable is True
ascii(object) Convert non-ASCII characters in an object to ASCII characters
bin(num) Convert a number to a binary string
bool([value]) Convert value to a boolean
bytearray(source) Convert source to a bytearray type
bytes(source) Convert source to a bytes type
callable(object) Check if an object is callable
chr(i) Convert ASCII code to character
classmethod(function) Convert a method into a class method
compile(source, filename, mode) Compile source into an executable code object
complex([real[, imag]]) Create a complex number from real and imaginary parts
delattr(object, name) Remove named attribute from object; raises exception if not exists
dict() Create a dictionary
dir([object]) Return list of object attributes
divmod(x, y) Divide x by y; returns quotient and remainder
enumerate(iterable, start=0) Combine an iterable into an index sequence with indices and data
eval(expression) Execute a single string expression and return result
exec(object, globals, locals) Execute complex code in object (string or code type); no return
filter(function, iterable) Filter iterable, keeping objects where function returns True
float([x]) Convert number or string to floating point type
format(value[, format_spec]) Format object as a string
frozenset([iterable]) Convert iterable to immutable set type
getattr(object, name[, default]) Get specified attribute of object; return default if not exists
globals() Return all global variables in dictionary form
hasattr(object, name) Check if object has specified attribute
hash(object) Get hash value of an object
help(object) Get help documentation for an object
hex(x) Convert an integer to a hexadecimal string
id(object) Return unique identifier of an object
input([prompt]) Read a line of user input and return it
int(x=0, base=10) Convert number or string to an integer
isinstance(object, classinfo) Check if an object is an instance of a class or its subclass
issubclass(object, classinfo) Check if a class is a subclass of another class
iter(object[, sentinel]) Generate an iterator from an object
len(s) Get length of an object (s must be sequence or collection)
list([iterable]) Convert an iterable to a list
locals() Return all local variables in dictionary form
map(function, iterable, …) Apply function to every element of iterable; returns result list
max(arg1, arg2, *args[, key]) Get maximum value from iterable or arguments
memoryview(obj) Wrap an object into a memory view object
min(arg1, arg2, *args[, key]) Get minimum value from iterable or arguments
next(iterator, default) Get next element of iterator; return default if no more elements
object() Return a new object
oct(x) Convert an integer to an octal string
open(file) Open a file and return a file object
ord(c) Convert a Unicode character to its ASCII or Unicode integer value
pow(x, y[, z]) Calculate x to the power of y, modulo z
print(*objects) Output objects to standard output or file stream
property() Generate attribute from getter, setter, deleter
range(start, stop[, step]) Return an immutable sequence of numbers
repr(obj) Return printable form of an object (suitable for interpreter)
reversed(seq) Reverse a sequence and return an iterator
round(number[, ndigits]) Round a floating-point number to specified decimal places
set([iterable]) Convert an iterable to a set type
setattr(object, name, value) Set attribute of object by name
slice(start, stop, step) Return a slice object
sorted(iterable[, key][, reverse]) Sort an iterable and return a new list
staticmethod(function) Convert a method to a static method
str(object=’') Convert an object to string type (human-readable)
sum(iterable, start) Sum all elements in an iterable
super(type[, object-or-type]) Get parent class
tuple(iterable) Convert an iterable to a tuple
type(object) Return type of an object
type(name, bases, dict) Create a new type object
vars(object) Return object attributes and values in dictionary form
zip(*iterables) Pack elements from multiple iterables into tuples; returns list
import(name) Dynamically import a module

List Methods

append(item) Add an element to the end of the list
extend(lst) Add all elements from lst to the list
insert(index, element) Insert element at specified position in list
remove(element) Find and remove the first occurrence of element from the left
index(element) Find and return index of first occurrence of element from the left
count(element) Return number of occurrences of specified element
pop(index) Remove and return element at specified position
reverse() Reverse the list
sort(key=…, reverse=…) Sort the list
copy() Shallow copy the list
clear() Remove all elements from the list

Dictionary Methods

clear() Remove all elements
copy() Shallow copy
fromkeys(sequence[, value]) Create new dictionary with sequence as keys and value as value
get(key[, value]) Return value for key; return value if not exists
items() Return all key-value pairs in dictionary (as tuples)
keys() Return all keys in dictionary
popitem() Remove and return an arbitrary (not random) element
setdefault(key[, default_value]) Insert key with default_value if not exists; return value for key
pop(key[, default]) Remove and return value for key; return default if not exists
values() Return all values in dictionary
update([other]) Update dictionary with other (dictionary or iterable of pairs)

Set Methods

remove(element) Remove specified element; raises exception if not exists
add(elem) Add element; does nothing if already exists
copy() Shallow copy the set
clear() Remove all elements from the set
a.difference(b) Return set of elements in a but not in b
a.difference_update(b) Remove elements in b from a
discard(x) Remove specified element if exists
a.intersection(*other_sets) Return intersection of a and other sets
a.intersection_update(*other_sets) Keep only elements found in a and all other sets
a.isdisjoint(b) Check if two sets have no common elements
a.issubset(b) Check if a is a subset of b
pop() Remove and return an arbitrary (not random) element from the set
a.symmetric_difference(b) Return set of elements in either a or b but not both
a.symmetric_difference_update(b) Update a with the symmetric difference of a and b
a.union(*other_sets) Return union of a and other sets
a.update(b) Update a with elements from b

Tuple Methods

index(element) Find and return position of element; raises exception if not exists
count(element) Count occurrences of specified element

Indexing and Slicing

a[x] Get the (x + 1)th element
a[-x] Get the xth element from the end
a[x:] Get from (x + 1)th element to the end
a[:x] Get from first element to (x + 1)th element
a[:-x] Get from first element to the xth element from the end
a[x:y] Get from (x + 1)th element to (y + 1)th element
a[:] Shallow copy of a

String Methods

capitalize() Capitalize the first character
center(width[, fillchar]) Center string and pad with fillchar to specified width
casefold() Convert string to lowercase (more aggressive than lower())
count(substring[, start[, end]]) Count occurrences of substring
endswith(suffix[, start[, end]]) Check if string ends with specified suffix
expandtabs(tabsize) Convert \t in string to specified number of spaces
encode(encoding=‘UTF-8’, errors=‘strict’) Encode string to any supported encoding
find(sub[, start[, end]]) Find position of substring from the left (-1 if not exists)
format(p0, p1, …, k0=v0, k1=v1, …) Format the string
index(sub[, start[, end]]) Find position of substring from the left (raises exception if not exists)
isalnum() Check if string is alphanumeric
isalpha() Check if string is alphabetic
isdecimal() Check if string consists only of decimal characters
isdigit() Check if string consists only of digits
isidentifier() Check if string is a valid identifier
islower() Check if string consists of lowercase letters
isnumeric() Check if string consists only of numeric characters (Unicode support)
isprintable() Check if string is printable
isspace() Check if string consists only of whitespace
istitle() Check if string is titlecased
isupper() Check if string consists only of uppercase letters
join(iterable) Join iterable of strings with specified delimiter
ljust(width[, fillchar]) Left-justify and pad string to specified width
rjust(width[, fillchar]) Right-justify and pad string to specified width
lower() Convert all characters to lowercase
upper() Convert all characters to uppercase
swapcase() Swap uppercase to lowercase and vice versa
lstrip([chars]) Strip specified characters from the left
rstrip([chars]) Strip specified characters from the right
strip([chars]) Strip specified characters from both sides
partition(separator) Split string at first separator from left; returns (before, sep, after)
maketrans(x[, y[, z]]) Create a translation mapping table
rpartition(separator) Split string at first separator from right; returns (before, sep, after)
translate(table) Replace characters using translation table
replace(old, new [, count]) Replace old substring with new, up to count times
rfind(sub[, start[, end]]) Find position of substring from the right (-1 if not exists)
rindex(sub[, start[, end]]) Find position of substring from the right (raises exception if not exists)
split([separator [, maxsplit]]) Split from left using separator, up to maxsplit times
rsplit([separator [, maxsplit]]) Split from right using separator, up to maxsplit times
splitlines([keepends]) Split string by lines
title() Convert string to titlecase
zfill(width) Left-pad string with zeros to specified width
format_map(mapping) Format string using dictionary mapping