Python Cheatsheet
Python Cheatsheet
Python Types:
• Numbers
• Strings
• Boolean
• Lists
• Dictionaries
• Tuples
• Sets
• None
Python Basics:
• Comparison Operators
• Logical Operators
• Loops
• Range
• Enumerate
• Counter
• Named Tuple
• OrderedDict
Functions:
• Functions
• Lambda
• Comprehensions
• Map,Filter,Reduce
• Ternary
• Any,All
• Closures
• Scope
Advanced Python:
• Modules
• Iterators
• Generators
• Decorators
• Class
• Exceptions
• Command Line Arguments
• File IO
• Useful Libraries
Numbers
Python's 2 main types for Numbers is int and float (or integers and
floating 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 remainder. 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
# Converting Strings to Numbers
age = input("How old are you?")
age = int(age)
pi = input("What is the value of pi?")
pi = float(pi)
Strings
'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 # **********
# 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
#Palindrome check
word = 'reviver'
p = bool(word.find(word[::-1]) + 1)
print(p) # True
Boolean
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']
Dictionaries
Also known as mappings or hash tables. They are key value pairs that
are guaranteed to retain order of insertion starting from Python 3.7
my_dict = {'name': 'Andrei Neagoie', 'age': 30, 'magic_power':
False}
my_dict['name'] # Andrei Neagoie
len(my_dict) # 3
list(my_dict.keys()) # ['name', 'age',
'magic_power']
list(my_dict.values()) # ['Andrei Neagoie', 30,
False]
list(my_dict.items()) # [('name', 'Andrei
Neagoie'), ('age', 30), ('magic_power', False)]
my_dict['favourite_snack'] = 'Grapes'# {'name': 'Andrei
Neagoie', 'age': 30, 'magic_power': False, 'favourite_snack':
'Grapes'}
my_dict.get('age') # 30 --> Returns None if
key does not exist.
my_dict.get('ages', 0 ) # 0 --> Returns default
(2nd param) if key is not found
#Remove key
del my_dict['name']
my_dict.pop('name', None)
my_dict.update({'cool': True})
# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False,
'favourite_snack': 'Grapes', 'cool': True}
{**my_dict, **{'cool': True} }
# {'name': 'Andrei Neagoie', 'age': 30, 'magic_power': False,
'favourite_snack': 'Grapes', 'cool': True}
new_dict =
dict([['name','Andrei'],['age',32],['magic_power',False]]) #
Creates a dict from collection of key-value pairs.
new_dict = dict(zip(['name','age','magic_power'],['Andrei',32,
False]))# Creates a dict from two collections.
new_dict = my_dict.pop('favourite_snack')
# Removes item from dictionary.
# Dictionary Comprehension
{key: value for key, value in new_dict.items() if key == 'age'
or key == 'name'} # {'name': 'Andrei', 'age': 32} --> Filter
dict by keys
Tuples
Like lists, but they are used for immutable things (that don't change)
my_tuple = ('apple','grapes','mango', 'grapes')
apple, grapes, mango, grapes = my_tuple# Tuple unpacking
len(my_tuple) # 4
my_tuple[2] # mango
my_tuple[-1] # 'grapes'
# Immutability
my_tuple[1] = 'donuts' # TypeError
my_tuple.append('candy')# AttributeError
# Methods
my_tuple.index('grapes') # 1
my_tuple.count('grapes') # 2
# Zip
list(zip([1,2,3], [4,5,6])) # [(1, 4), (2, 5), (3, 6)]
# unzip
z = [(1, 2), (3, 4), (5, 6), (7, 8)] # Some output of zip()
function
unzip = lambda z: list(zip(*z))
unzip(z)
Sets
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
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
Named Tuple
OrderedDict
Functions
add(1, 2, 3) # 6
Ordering of parameters:
def f(*args): # f(1, 2, 3)
def f(x, *args): # f(1, 2, 3)
def f(*args, z): # f(1, 2, z=3)
def f(x, *args, z): # f(1, 2, z=3)
Other Uses of *
[*[1,2,3], *[4]] # [1, 2, 3, 4]
{*[1,2,3], *[4]} # {1, 2, 3, 4}
(*[1,2,3], *[4]) # (1, 2, 3, 4)
{**{'a': 1, 'b': 2}, **{'c': 3}}# {'a': 1, 'b': 2, 'c': 3}
head, *body, tail = [1,2,3,4,5]
Lambda
# lambda: <return_value>
# lambda <argument1>, <argument2>: <return_value>
# Factorial
from functools import reduce
n = 3
factorial = reduce(lambda x, y: x*y, range(1, n+1))
print(factorial) #6
# Fibonacci
fib = lambda n : n if n <= 1 else fib(n-1) + fib(n-2)
result = fib(10)
print(result) #55
Comprehensions
Ternary Condition
Any All
Closures
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
>>> counter = get_counter()
>>> counter(), counter(), counter()
(1, 2, 3)
Modules
Generators
Decorators
Debugger Example
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
@classmethod
def get_class_name(cls):
return cls.__name__
Inheritance
```python class Person: def __init__(self, name, age): self.name = name self.age = age
class Employee(Person): def init(self, name, age, staff_num):
super().init(name, age) self.staff_num = staff_num
MRO determines the order in which parent classes are traversed when
searching for a method:
>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
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
Finally
```python
import sys
script_name = sys.argv[0]
arguments = sys.argv[1:]
File IO
Opens a file and returns a corresponding file object.
<file> = open('<path>', mode='r', encoding=None)
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.
File
<file>.seek(0) # Moves to the start of the
file.
<str/bytes> = <file>.readline() # Returns a line.
<list> = <file>.readlines() # Returns a list of lines.
<file>.write(<str/bytes>) # Writes a string or bytes
object.
<file>.writelines(<list>) # Writes a list of strings
or bytes objects.
Useful Libraries
CSV
import csv
JSON
import json
<str> = json.dumps(<object>, ensure_ascii=True, indent=None)
<object> = json.loads(<str>)
Pickle
import pickle
<bytes> = pickle.dumps(<object>)
<object> = pickle.loads(<bytes>)
Read Object from File
def read_pickle_file(filename):
with open(filename, 'rb') as file:
return pickle.load(file)
Profile
Basic
from time import time
start_time = time() # Seconds since
...
duration = time() - start_time
Math
from math import e, pi
from math import cos, acos, sin, asin, tan, atan, degrees,
radians
from math import log, log10, log2
from math import inf, nan, isinf, isnan
Statistics
from statistics import mean, median, variance, pvariance, pstdev
Random
from random import random, randint, choice, shuffle
random() # random float between 0 and 1
randint(0, 100) # random integer between 0 and 100
random_el = choice([1,2,3,4]) # select a random element from
list
shuffle([1,2,3,4]) # shuffles a list
Datetime
• Module 'datetime' provides 'date' <D>, 'time' <T>,
'datetime' <DT> and 'timedelta' <TD> classes. All are immutable
and hashable.
• Time and datetime 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 system's timezone.
from datetime import date, time, datetime, timedelta
from dateutil.tz import UTC, tzlocal, gettz
Constructors
<D> = date(year, month, day)
<T> = time(hour=0, minute=0, second=0, microsecond=0,
tzinfo=None, fold=0)
<DT> = datetime(year, month, day, hour=0, minute=0, second=0,
...)
<TD> = timedelta(days=0, seconds=0, microseconds=0,
milliseconds=0,
minutes=0, hours=0, weeks=0)
Timezone
<tz> = UTC # UTC timezone.
<tz> = tzlocal() # Local timezone.
<tz> = gettz('<Cont.>/<City>') # Timezone from
'Continent/City_Name' str.
<DTa> = <DT>.astimezone(<tz>) # Datetime,
converted to passed timezone.
<Ta/DTa> = <T/DT>.replace(tzinfo=<tz>) # Unconverted object
with new timezone.
Regex
import re
<str> = re.sub(<regex>, new, text, count=0) # Substitutes all
occurrences.
<list> = re.findall(<regex>, text) # Returns all
occurrences.
<list> = re.split(<regex>, text, maxsplit=0) # Use brackets in
regex to keep the matches.
<Match> = re.search(<regex>, text) # Searches for
first occurrence of pattern.
<Match> = re.match(<regex>, text) # Searches only
at the beginning of the text.
Match Object
<str> = <Match>.group() # Whole match.
<str> = <Match>.group(1) # Part in first bracket.
<tuple> = <Match>.groups() # All bracketed parts.
<int> = <Match>.start() # Start index of a match.
<int> = <Match>.end() # Exclusive end index of a match.
Special Sequences
Expressions below hold true for strings that contain only ASCII
characters. Use capital letters for negation.
'\d' == '[0-9]' # Digit
'\s' == '[ \t\n\r\f\v]' # Whitespace
'\w' == '[a-zA-Z0-9_]' # Alphanumeric