Python ZTM Cheatsheet: Andrei Neagoie
Python ZTM Cheatsheet: Andrei Neagoie
PYTHON
ZTM
CHEATSHEET
Andrei Neagoie
V1.04
HEEELLLOOOOO!
I’m Andrei Neagoie, Founder and Lead Instructor of the Zero To Mastery Academy.
A er working as a Senior So ware Developer over the years, I now dedicate 100% of my
me teaching others valuable so ware development skills, help them break into the
tech industry, and advance their careers. In only a few years, over 400,000
students around the world have taken my courses and many of them are now working at
top er companies like Apple, Google, Amazon, Tesla, IBM, UNIQLO, just to name a few.
This cheatsheet provides you with all the Python essen als in one place. If you want to
learn everything Python has to o er and become a Python expert, check out my
Complete Python Developer in 2021 course and enjoy an hour of free lessons (click
PREVIEW next to any of the lessons): Complete Python Developer in 2021.
Happy Coding!
Andrei
P.S. I also recently wrote a book called Principles For Programmers. You can download
the first five chapters for free here.
ti
ft
ti
ft
ft
ff
ti
CONTENTS
Python Types:
Numbers, Strings, Boolean, Lists, Dic onaries, Tuples, Sets, None
Python Basics:
Comparison Operators, Logical Operators, Loops, Range, Enumerate,
Counter, Named Tuple, OrderedDict
Func ons:
Func ons, Lambda, Comprehensions, Map,Filter,Reduce, Ternary, Any,All,
Closures, Scope
Advanced Python:
Modules, Iterators, Generators, Decorators, Class, Excep ons,
Command Line Arguments, File IO, Useful Libraries
ti
ti
NUMBERS
Python's 2 main types for Numbers is int and oat (or integers and oa ng point
numbers).
type(1) # int
type(-10) # int
type(0) # int
type(0.0) # float
type(2.2) # float
type(4E2) # float - 4*10 to the power of 2
# Arithmetic
10 + 3 # 13
10 - 3 # 7
10 * 3 # 30
10 ** 3 # 1000
10 / 3 # 3.3333333333333335
10 // 3 # 3 --> floor division - no decimals and returns an int
10 % 3 # 1 --> modulo operator - return the reminder. Good for deciding if
number is even or odd
# Basic Functions
pow(5, 2) # 25 --> like doing 5**2
abs(-50) # 50
round(5.46) # 5
round(5.468, 2)# 5.47 --> round to nth digit
bin(512) # '0b1000000000' --> binary format
hex(512) # '0x200' --> hexadecimal format
age = int(age)
fl
fl
ti
STRINGS
Strings in python are stored as sequences of le ers in memory.
type('Hellloooooo') # str
'I\'m thirsty'
"I'm thirsty"
"\n" # new line
"\t" # adds a tab
'Hey you!'[4] # y
name = 'Andrei Neagoie'
name[4] # e
name[:] # Andrei Neagoie
name[1:] # ndrei Neagoie
name[:1] # A
name[-1] # e
name[::1] # Andrei Neagoie
name[::-1] # eiogaeN ierdnA
name[0:10:2]# Ade e
# : is called slicing and has the format [ start : end : step ]
'Hi there ' + 'Timmy' # 'Hi there Timmy' --> This is called string concatenation
'*'*10 # **********
tt
# Basic Functions
len('turtle') # 6
# Basic Methods
' I am alone '.strip() # 'I am alone' --> Strips all whitespace
characters from both ends.
'On an island'.strip('d') # 'On an islan' --> # Strips all passed
characters from both ends.
'but life is good!'.split() # ['but', 'life', 'is', 'good!']
'Help me'.replace('me', 'you') # 'Help you' --> Replaces first with
second param
'Need to make fire'.startswith('Need')# True
'and cook rice'.endswith('rice') # True
'bye bye'.index(e) # 2
'still there?'.upper() # STILL THERE?
'HELLO?!'.lower() # hello?!
'ok, I am done.'.capitalize() # 'Ok, I am done.'
'oh hi there'.find('i') # 4 --> returns the starting
index position of the first occurrence
'oh hi there'.count('e') # 2
# String Formatting
name1 = 'Andrei'
name2 = 'Sunny'
print(f'Hello there {name1} and {name2}') # Hello there Andrei and
Sunny - Newer way to do things as of python 3.6
print('Hello there {} and {}'.format(name1, name2)) # Hello there Andrei and
Sunny
print('Hello there %s and %s' %(name1, name2)) # Hello there Andrei and
Sunny --> you can also use %d, %f, %r for integers, floats, string
representations of objects respectively
word = 'reviver'
p = bool(word.find(word[::-1]) + 1
print(p) # True
BOOLEAN
True or False. Used in a lot of comparison and logical opera ons in Python.
bool(True)
bool(False)
# all of the below evaluate to False. Everything else will evaluate to True in
Python.
print(bool(None))
print(bool(False))
print(bool(0))
print(bool(0.0))
print(bool([]))
print(bool({}))
print(bool(()))
print(bool(''))
print(bool(range(0)))
print(bool(set()))
# See Logical Operators and Comparison Operators section for more on booleans.
ti
LISTS
Unlike strings, lists are mutable sequences in python.
my_list = [1, 2, '3', True]# We assume this list won't mutate for each example
below
len(my_list) # 4
my_list.index('3') # 2
my_list.count(2) # 1 --> count how many times 2 appears
my_list[3] # True
my_list[1:] # [2, '3', True]
my_list[:1] # [1]
my_list[-1] # True
my_list[::1] # [1, 2, '3', True]
my_list[::-1] # [True, '3', 2, 1]
my_list[0:3:2] # [1, '3']
# Add to List
my_list * 2 # [1, 2, '3', True, 1, 2, '3', True]
my_list + [100] # [1, 2, '3', True, 100] --> doesn't mutate original
list, creates new one
my_list.append(100) # None --> Mutates original list to [1, 2, '3', True,
100] # Or: <list> += [<el>]
my_list.extend([100, 200]) # None --> Mutates original list to [1, 2, '3', True,
100, 200]
my_list.insert(2, '!!!') # None --> [1, 2, '!!!', '3', True] - Inserts item
at index and moves the rest to the right.
# Copy a List
new_basket = basket.copy()
new_basket2 = basket[:]
[1,2,3].pop() # 3 --> mutates original list, default index in the pop method
[1,2,3].clear() # None --> mutates original list and removes all items: []
del [1,2,3][0] #
# Ordering
# Useful operations
1 in [1,2,5,3] # True
min([1,2,3,4,5])# 1
max([1,2,3,4,5])# 5
sum([1,2,3,4,5])# 15
mList = [63, 21, 30, 14, 35, 26, 77, 18, 49, 10
print(first) #6
print(last) #1
# Matrix
matrix = [[1,2,3], [4,5,6], [7,8,9]]
matrix[2][0] # 7 --> Grab first first of the third item in the matrix object
# List Comprehensions
# Advanced Functions
sum_of_elements = sum([1,2,3,4,5]) # 15
'hi', 'you']
sorted_by_key = sorted([
with open("myfile.txt") as f
DICTIONARIES
Also known as mappings or hash tables. They are key value pairs that are guaranteed
to retain order of inser on star ng from Python 3.7.
#Remove key
del my_dict['name']
my_dict.pop('name', None)
ti
'cool': True}
'cool': True}
# Dictionary Comprehension
{key: value for key, value in new_dict.items() if key == 'age' or key == 'name'}
len(my_tuple) # 4
my_tuple[2] # mango
my_tuple[-1] # 'grapes'
# Immutability
my_tuple.append('candy')# AttributeError
# Methods
my_tuple.index('grapes') # 1
my_tuple.count('grapes') # 2
# Zip
# unzip
z = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip() function
unzip(z
SETS
Unordered collec on of unique elements.
my_set = set()
my_set.add(1) # {1}
new_list = [1,2,3,3,3,4,4,5,6,1]
set(new_list) # {1, 2, 3, 4, 5, 6}
my_set.clear() # {}
set1 = {1,2,3}
set2 = {3,4,5}
set1.issuperset(set2) # False
null intersection.
# Frozenset
set.
<frozenset> = frozenset(<collection>)
ti
NONE
None is used for absence of a value and can be used to show nothing has been
assigned to an object.
type(None) # NoneType
a = None
COMPARISON OPERATORS
== # equal values
!= # not equal
> # left operand is greater than right operand
< # left operand is less than right operand
>= # left operand is greater than or equal to right operand
<= # left operand is less than or equal to right operand
<element> is <element> # check if two operands refer to same object in memory
LOGICAL OPERATORS
1 < 2 and 4 > 1 # True
1 > 3 or 4 > 1 # True
1 is not 4 # True
not True # False
1 not in [2,3,4]# True
LOOPS
my_list = [1,2,3]
my_tuple = (1,2,3)
my_list2 = [(1,2), (3,4), (5,6)]
my_dict = {'a': 1, 'b': 2. 'c': 3}
RANGE
list(range(0,10,2))# [0, 2, 4, 6, 8]
ENUMERATE
for i, el in enumerate('helloo'):
print(f'{i}, {el}')
# 0, h
# 1, e
# 2, l
# 3, l
# 4, o
# 5, o
COUNTER
from collections import Counte
counter.most_common()[0] # ('blue', 3)
NAMED TUPLE
• Tuple is an immutable and hashable list.
• Named tuple is its subclass with named elements.
ORDEREDDICT
Maintains order of inser on.
ti
FUNCTIONS
*args and **kwargs
Splat (*) expands a collec on into posi onal arguments, while spla y-splat (**)
expands a dic onary into keyword arguments.
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
some_func(*args, **kwargs) # same as some_func(1, 2, x=3, y=4, z=5)
* Inside Func on De ni on
Splat combines zero or more posi onal arguments into a tuple, while spla y-splat
combines zero or more keyword arguments into a dic onary.
def add(*a):
return sum(a)
add(1, 2, 3) # 6
fi
ti
ti
ti
ti
ti
tt
tt
Ordering of parameters:
def f(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2,
z=3) | f(1, 2, 3)
def f(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2,
z=3) | f(1, 2, 3)
def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3)
Other Uses of *
[*[1,2,3], *[4]] # [1, 2, 3, 4]
LAMBDA
# lambda: <return_value>
# Factorial
n = 3
# Fibonacci
result = fib(10
print(result) #55
COMPREHENSIONS
<list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
<set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
<iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
<dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
TERNARY CONDITION
# <expression_if_true> if <condition> else <expression_if_false>
9,10]
ANY ALL
any([False, True, False])# True if at least one item in collection is truthy,
False if empty.
CLOSURES
We have a closure in Python when:
• A nested func on references a value of its enclosing func on and then
• The enclosing func on returns the nested func on.
def get_multiplier(a):
def out(b):
return a *
return out
• If mul ple nested func ons within enclosing func on reference the same value,
that value gets shared.
• To dynamically access func on's rst free variable use
'<func on>.__closure__[0].cell_contents'.
ti
b
ti
ti
fi
ti
ti
ti
SCOPE
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'.
def get_counter():
i = 0
def out():
nonlocal
i += 1
return
return out
MODULES
import <module_name>
from <module_name> import <function_name>
import <module_name> as
from <module_name> import <function_name> as m_functio
from <module_name> import *
ITERATORS
In this cheatsheet '<collec on>' can also mean an iterator.
<iter> = iter(<collection>)
<iter> = iter(<function>, to_exclusive) # Sequence of return values until
'to_exclusive'.
<el> = next(<iter> [, default]) # Raises StopIteration or returns 'default'
on end.
GENERATORS
Convenient way to implement the iterator protocol.
while True:
yield star
start += step
DECORATORS
A decorator takes a func on, adds some func onality and returns it.
@decorator_name
def function_that_gets_passed_to_decorator():
...
ti
ti
ti
DEBUGGER EXAMPLE
Decorator that prints func on's name every me it gets called.
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return ou
@debug
def add(x, y):
return x + y
CLASS
User de ned objects are created using the class keyword.
class <name>:
age = 80 # Class Object Attribute
def __init__(self, a):
self.a = a # Object Attribute
@classmethod
def get_class_name(cls):
return cls.__name__
fi
ti
s
ti
ti
ti
INHERITANCE
class Person:
def __init__(self, name, age):
self.name = nam
self.age = ag
class Employee(Person):
def __init__(self, name, age, staff_num):
super().__init__(name, age)
self.staff_num = staff_num
MULTIPLE INHERITANCE
class A: pass
class B: pass
MRO determines the order in which parent classes are traversed when searching for a
method:
>>> C.mro()
EXCEPTIONS
try:
5/0
except ZeroDivisionError:
print("No division by zero!")
while True:
try:
x = int(input('Enter your age: '))
except ValueError:
print('Oops! That was no valid number. Try again...')
else: # code that depends on the try block running successfully should be
placed in the else block.
print('Carry on!')
break
RAISING EXCEPTION
raise ValueError('some error message')
FINALLY
try:
raise KeyboardInterrup
except:
print('oops')
finally:
print('All done!')
script_name = sys.argv[0]
arguments = sys.argv[1:]
FILE IO
Opens a le and returns a corresponding le object.
Modes
• 'r' - Read (default).
• 'w' - Write (truncate).
• 'x' - Write or fail if the le 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.
File
<file>.seek(0) # Moves to the start of the file.
fi
s
fi
fi
print(line)
file.write(text)
file.write(text)
USEFUL LIBRARIES
CSV
import csv
def read_csv_file(filename):
writer.writerows(rows)
JSON
import jso
<str> = json.dumps(<object>, ensure_ascii=True, indent=None)
<object> = json.loads(<str>)
def read_json_file(filename):
with open(filename, encoding='utf-8') as file:
return json.load(file)
Pickle
import pickl
<bytes> = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)
def read_pickle_file(filename):
return pickle.load(file)
pickle.dump(an_object, file)
Pro le
Basic
...
Math
from math import cos, acos, sin, asin, tan, atan, degrees, radian
Sta s cs
Random
ti
Date me
• Module 'date me' provides 'date' <D>, ' me' <T>, 'date me' <DT> and
' medelta' <TD> classes. All are immutable and hashable.
• Time and date me can be 'aware' <a>, meaning they have de ned mezone, or
'naive' <n>, meaning they don't.
• If object is naive it is presumed to be in system's mezone.
Constructors
Now
ti
ti
ti
ti
ti
ti
ti
fi
ti
Timezone
Regex
import r
the matches.
of pattern.
of the text.
Match Object
Special Sequences
Expressions below hold true for strings that contain only ASCII characters. Use
capital le ers for nega on.
CREDITS
Inspired by: h ps://github.com/gto76/python-cheatsheet
ti