Python Cheat Sheet
Python Cheat Sheet
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 o
# Arithmetic
10 + 3 # 13
10 - 3 # 7
10 * 3 # 30
10 ** 3 # 1000
10 / 3 # 3.3333333333333335
10 // 3 # 3 --> floor division - no dec
10 % 3 # 1 --> modulo operator - retur
# 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
bin(512) # '0b1000000000' --> bi
hex(512) # '0x200' --> hexadecima
'*'*10 # **********
# Basic Functions
len('turtle') # 6
# Basic Methods
' I am alone '.strip() #
'On an island'.strip('d') #
'but life is good!'.split() #
'Help me'.replace('me', 'you') #
'Need to make fire'.startswith('Need')#
'and cook rice'.endswith('rice') #
'bye bye'.index('e') #
'still there?'.upper() #
'HELLO?!'.lower() #
'ok, I am done.'.capitalize() #
'oh hi there'.find('i') #
'oh hi there'.count('e') #
# String Formatting
name1 = 'Andrei'
name2 = 'Sunny'
print(f'Hello there {name1} and {name2}
print('Hello there {} and {}'.format(na
print('Hello there %s and %s' %(name1,
#Palindrome check
word = 'reviver'
p = bool(word.find(word[::-1]) + 1)
print(p) # True
Boolean
Boolean
bool(True)
bool(False)
Lists
# Add to List
my_list * 2 # [1, 2, '3'
my_list + [100] # [1, 2, '3'
my_list.append(100) # None --> M
my_list.extend([100, 200]) # None --> M
my_list.insert(2, '!!!') # None -->
# Copy a List
basket = ['apples', 'pears', 'oranges']
new_basket = basket.copy()
new_basket2 = basket[:]
# Ordering
# Ordering
[1,2,5,3].sort() # None --> Mut
[1,2,5,3].sort(reverse=True) # None -->
[1,2,5,3].reverse() # None --> Mut
sorted([1,2,5,3]) # [1, 2, 3, 5]
list(reversed([1,2,5,3]))# [3, 5, 2, 1]
# 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
# Matrix
matrix = [[1,2,3], [4,5,6], [7,8,9]]
matrix[2][0] # 7 --> Grab first first o
# List Comprehensions
# new_list[<action> for <item> in <iter
a = [i for i in 'hello']
b = [i*2 for i in [1,2,3]]
c = [i for i in range(0,10) if i % 2 ==
# Advanced Functions
list_of_chars = list('Helloooo')
sum_of_elements = sum([1,2,3,4,5])
element_sum = [sum(pair) for pair in zi
sorted_by_second = sorted(['hi','you','
sorted_by_key = sorted([
{'name': 'Bina',
{'name':'Andy',
{'name': 'Zoey',
key=lambda el: (
Dictionaries
#Remove key
del my_dict['name']
my_dict.pop('name', None)
my_dict.update({'cool': True})
{**my_dict, **{'cool': True} }
new_dict = dict([['name','Andrei'],['ag
new_dict = dict(zip(['name','age','magi
new_dict = my_dict.pop('favourite_snack
# Dictionary Comprehension
{key: value for key, value in new_dict.
Tuples
# Immutability
my_tuple[1] = 'donuts' # TypeError
my_tuple.append('candy')# AttributeErro
# Methods
my_tuple.index('grapes') # 1
my_tuple.count('grapes') # 2
# Zip
list(zip([1,2,3], [4,5,6])) # [(1, 4),
# unzip
z = [(1, 2), (3, 4), (5, 6), (7, 8)] #
unzip = lambda z: list(zip(*z))
unzip(z)
Sets
my_set = set()
my_set.add(1) # {1}
my_set.add(100)# {1, 100}
my_set.add(100)# {1, 100} --> no duplic
new_list = [1,2,3,3,3,4,4,5,6,1]
set(new_list) # {1, 2, 3, 4,
set1 = {1,2,3}
set2 = {3,4,5}
set3 = set1.union(set2) #
set4 = set1.intersection(set2) #
set5 = set1.difference(set2) #
set6 = set1.symmetric_difference(set2)#
set1.issubset(set2) #
set1.issuperset(set2) #
set1.isdisjoint(set2) #
# Frozenset
# hashable --> it can be used as a key
<frozenset> = frozenset(<collection>)
None
type(None) # NoneType
a = None
Comparison Operators
== # equal values
!= # not equal
> # left operand is
< # left operand is
>= # left operand is
<= # left operand is
<element> is <element> # check if two o
Logical Operators
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
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 Counter
colors = ['red', 'blue', 'yellow', 'blu
counter = Counter(colors)# Counter({'bl
counter.most_common()[0] # ('blue', 3)
Named Tuple
OrderedDict
Maintains order of insertion
from collections import OrderedDict
# Store each person's languages, keepin
programmers = OrderedDict()
programmers['Tim'] = ['python', 'javasc
programmers['Sarah'] = ['C++']
programmers['Bia'] = ['Ruby', 'Python',
Functions
args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
some_func(*args, **kwargs) # same as so
def add(*a):
return sum(a)
add(1, 2, 3) # 6
Ordering of parameters:
Other Uses of *
Lambda
# lambda: <return_value>
# lambda <argument1>, <argument2>: <ret
# Factorial
from functools import reduce
n = 3
factorial = reduce(lambda x, y: x*y, ra
print(factorial) #6
# Fibonacci
fib = lambda n : n if n <= 1 else fib(n
result = fib(10)
print(result) #55
Comprehensions
Ternary Condition
# <expression_if_true> if <condition> e
Any All
any([False, True, False])# True if at l
all([True,1,3,True]) # True if all
Closures
def get_multiplier(a):
def out(b):
return a * b
return out
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
i += 1
return i
return out
Modules
Iterators
<iter> = iter(<collection>)
<iter> = iter(<function>, to_exclusive)
<el> = next(<iter> [, default])
Generators
Decorators
@decorator_name
def function_that_gets_passed_to_decora
...
Debugger Example
**Decorator that prints function's name every time it gets
called.**
def debug(func):
@wraps(func)
def out(*args, **kwargs):
print(func.__name__)
return func(*args, **kwargs)
return out
@debug
def add(x, y):
return x + y
Class
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__
Inheritance
```python class Person: def __init__(self, name, age): self.name =
name self.age = age
<h2 id="multiple-inheritance">Multiple
```python
class A: pass
class B: pass
class C(A, B): pass
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>,
Exceptions
try:
5/0
except ZeroDivisionError:
print("No division by zero!")
while True:
try:
Raising Exception
```python raise ValueError('some error message') ```
Finally
```python try: raise KeyboardInterrupt except: print('oops')
nally: print('All done!')
<h2 id="command-line-arguments">Command
```python
import sys
script_name = sys.argv[0]
arguments = sys.argv[1:]
File IO
Modes
'r' - Read (default).
'a' - Append.
File
<file>.seek(0) # M
<str/bytes> = <file>.readline() # R
<list> = <file>.readlines() # R
<file>.write(<str/bytes>) # W
<file>.writelines(<list>) # W
def read_file(filename):
with open(filename, encoding='utf-8
return file.readlines() # or re
Useful Libraries
CSV
import csv
def read_csv_file(filename):
with open(filename, encoding='utf-8
return csv.reader(file, delimit
JSON
import json
<str> = json.dumps(<object>, ensure_
<object> = json.loads(<str>)
Pickle
import pickle
<bytes> = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
Pro le
Pro le
Basic
Math
Statistics
Random
Datetime
Datetime
Module 'datetime' provides 'date' <D> , 'time'
<T> , 'datetime' <DT> and 'timedelta' <TD>
classes. All are immutable and hashable.
Constructors
Now
Now
<D/DTn> = D/DT.today()
<DTn> = DT.utcnow()
<DTa> = DT.now(<tz>)
Timezone
<tz> = UTC
<tz> = tzlocal()
<tz> = gettz('<Cont.>/<City>')
<DTa> = <DT>.astimezone(<tz>)
<Ta/DTa> = <T/DT>.replace(tzinfo=<tz>)
Regex
import re
<str> = re.sub(<regex>, new, text, co
<list> = re.findall(<regex>, text)
<list> = re.split(<regex>, text, maxsp
<Match> = re.search(<regex>, text)
<Match> = re.match(<regex>, text)
Match Object
Special Sequences
Credits