0% found this document useful (0 votes)
11 views

Python Cheat Sheet

The document provides an overview of various data types and structures in Python, including numbers, strings, lists, dictionaries, tuples, sets, and more. It covers basic operations, methods, and functions associated with each type, as well as examples of usage. Additionally, it discusses control flow, loops, and advanced concepts like named tuples and ordered dictionaries.

Uploaded by

Naser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Cheat Sheet

The document provides an overview of various data types and structures in Python, including numbers, strings, lists, dictionaries, tuples, sets, and more. It covers basic operations, methods, and functions associated with each type, as well as examples of usage. Additionally, it discusses control flow, loops, and advanced concepts like named tuples and ordered dictionaries.

Uploaded by

Naser
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Numbers

Python's 2 main types for Numbers is int and oat


(or integers and oating 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 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

True or False. Used in a lot of comparison and


logical operations in Python

bool(True)
bool(False)

# all of the below evaluate to False. E


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

Lists

Unlike strings, lists are mutable sequences in


python

my_list = [1, 2, '3', True]# We assume


len(my_list) # 4
my_list.index('3') # 2
my_list.count(2) # 1 --> coun
my_list[3] # True
my_list[1:] # [2, '3', T
my_list[:1] # [1]
my_list[-1] # True
my_list[::1] # [1, 2, '3'
my_list[::-1] # [True, '3'
my_list[0:3:2] # [1, '3']

# : is called slicing and has the forma

# 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 -->

' '.join(['Hello','There'])# 'Hello The

# Copy a List
basket = ['apples', 'pears', 'oranges']
new_basket = basket.copy()
new_basket2 = basket[:]

# Remove from List


[1,2,3].pop() # 3 --> mutates origin
[1,2,3].pop(1) # 2 --> mutates origin
[1,2,3].remove(2)# None --> [1,3] Remov
[1,2,3].clear() # None --> mutates ori
del [1,2,3][0] #

# 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

# Get First and Last element of a list


mList = [63, 21, 30, 14, 35, 26, 77, 18
first, *x, last = mList
print(first) #63
print(last) #10

# Matrix
matrix = [[1,2,3], [4,5,6], [7,8,9]]
matrix[2][0] # 7 --> Grab first first o

# Looping through a matrix by rows:


mx = [[1,2,3],[4,5,6]]
for row in range(len(mx)):
for col in range(len(mx[0])):
print(mx[row][col]) # 1 2 3 4 5

# Transform into a list:


[mx[row][col] for row in range(len(mx))

# Combine columns with zip and *:


[x for x in zip(*mx)] # [(1, 3), (2, 4)

# 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: (

# Read line of a file into a list


with open("myfile.txt") as f:
lines = [line.strip() for line in f]

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


g y

my_dict = {'name': 'Andrei Neagoie', 'a


my_dict['name'] #
len(my_dict) #
list(my_dict.keys()) #
list(my_dict.values()) #
list(my_dict.items()) #
my_dict['favourite_snack'] = 'Grapes'#
my_dict.get('age') #
my_dict.get('ages', 0 ) #

#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

Like lists, but they are used for immutable things


(that don't change)
my_tuple = ('apple','grapes','mango', '
apple, grapes, mango, grapes = my_tuple
len(my_tuple)
my_tuple[2]
my_tuple[-1]

# 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

Unordered collection of unique elements.

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,

my_set.remove(100) # {1} --> Raise


my_set.discard(100) # {1} --> Doesn
my_set.clear() # {}
new_set = {1,2,3}.copy()# {1,2,3}

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

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
< # left operand is
>= # left operand is
<= # left operand is
<element> is <element> # check if two o

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

if <condition that evaluates to boolean


# perform action1

elif <condition that evaluates to boole


# perform action2
else:
# perform action3

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}

for num in my_list:


print(num) # 1, 2, 3

for num in my_tuple:


print(num) # 1, 2, 3

for num in my_list2:


print(num) # (1,2), (3,4), (5,6)

for num in '123':


print(num) # 1, 2, 3

for k,v in my_dict.items(): # Dictionar


print(k) # 'a', 'b', 'c'
print(v) # 1, 2, 3

while <condition that evaluates to bool


# action
if <condition that evaluates to boole
break # break out of while loop
if <condition that evaluates to boole
continue # continue to the next lin
# waiting until user quits
msg = ''
while msg != 'quit':
msg = input("What should I do?")
print(msg)

Range

range(10) # range(0, 10) --> 0


range(1,10) # range(1, 10)
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 Counter
colors = ['red', 'blue', 'yellow', 'blu
counter = Counter(colors)# Counter({'bl
counter.most_common()[0] # ('blue', 3)

Named Tuple

Tuple is an immutable and hashable list.

Named tuple is its subclass with named


elements.

from collections import namedtuple


Point = namedtuple('Point', 'x y')
p = Point(1, y=2)# Point(x=1, y=2)
p[0] # 1
p.x # 1
getattr(p, 'y') # 2
p._fields # Or: Point._fields #(

from collections import namedtuple


Person = namedtuple('Person', 'name hei
person = Person('Jean-Luc', 187)
f'{person.height}' # '187'
'{p.height}'.format(p=person)# '187'

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',

for name, langs in programmers.items():


print(name + '-->')
for lang in langs:
print('\t' + lang)

Functions

*args and **kwargs

Splat (*) expands a collection into positional


arguments, while splatty-splat (**) expands a
dictionary into keyword arguments.

args = (1, 2)
kwargs = {'x': 3, 'y': 4, 'z': 5}
some_func(*args, **kwargs) # same as so

* Inside Function De nition

Splat combines zero or more positional


p p
arguments into a tuple, while splatty-splat
combines zero or more keyword arguments into a
dictionary.

def add(*a):
return sum(a)

add(1, 2, 3) # 6

Ordering of parameters:

def f(*args): # f(1, 2


def f(x, *args): # f(1, 2
def f(*args, z): # f(1, 2
def f(x, *args, z): # f(1, 2

def f(**kwargs): # f(x=1,


def f(x, **kwargs): # f(x=1,

def f(*args, **kwargs): # f(x=1,


def f(x, *args, **kwargs): # f(x=1,
def f(*args, y, **kwargs): # f(x=1,
def f(x, *args, z, **kwargs): # f(x=1,

Other Uses of *

[*[1,2,3], *[4]] # [1, 2


{*[1,2,3], *[4]} # {1, 2
(*[1,2,3], *[4]) # (1, 2
{**{'a': 1, 'b': 2}, **{'c': 3}}# {'a':

head *bod tail [1 2 3 4 5]


head, *body, tail = [1,2,3,4,5]

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

<list> = [i+1 for i in range(10)]


<set> = {i for i in range(10) if i > 5
<iter> = (i+5 for i in range(10))
<dict> = {i: i*2 for i in range(10)}
output = [i+j for i in range(3) for j i

# Is the same as:


output = []
for i in range(3):
for j in range(3):
output.append(i+j)

Ternary Condition

# <expression_if_true> if <condition> e

[a if a else 'zero' for a in [0, 1, 0,

Map Filter Reduce

from functools import reduce


list(map(lambda x: x + 1, range(10)))
list(filter(lambda x: x > 5, range(10))
reduce(lambda acc, x: acc + x, range(10

Any All
any([False, True, False])# True if at l
all([True,1,3,True]) # True if all

Closures

We have a closure in Python when:

A nested function references a value of its


enclosing function and then

the enclosing function returns the nested


function.

def get_multiplier(a):
def out(b):
return a * b
return out

>>> multiply_by_3 = get_multiplier(3)


>>> multiply_by_3(10)
30

If multiple nested functions within enclosing


function reference the same value, that value
gets shared.

To dynamically access function's rst free


o dy a ca y access u ct o s st ee
variable use
'<function>.__closure__[0].cell_contents' .

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

if __name__ == '__main__': # Runs main(


main()
import <module_name>
from <module_name> import <function_nam
import <module_name> as m
from <module_name> import <function_nam
from <module_name> import *

Iterators

In this cheatsheet '<collection>' can also


mean an iterator.

<iter> = iter(<collection>)
<iter> = iter(<function>, to_exclusive)
<el> = next(<iter> [, default])

Generators

Convenient way to implement the iterator


protocol.

def count(start, step):


while True:
yield start
start += step
>>> counter = count(10, 2)
>>> next(counter), next(counter), next(
(10, 12, 14)

Decorators

A decorator takes a function, adds some


functionality and returns it.

@decorator_name
def function_that_gets_passed_to_decora
...

Debugger Example
**Decorator that prints function's name every time it gets
called.**

from functools import wraps

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

Wraps is a helper decorator that copies


metadata of function add() to function out().

Without it 'add.__name__' would return


'out' .

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__

Inheritance
```python class Person: def __init__(self, name, age): self.name =
name self.age = age

class Employee(Person): def init(self, name, age,


p y ( ) ( g
staff_num): super().init(name, age) self.staff_num
= staff_num

<h2 id="multiple-inheritance">Multiple
```python
class A: pass
class B: pass
class C(A, B): pass

MRO determines the order in which parent


classes are traversed when searching for a
method:

>>> C.mro()
[<class 'C'>, <class 'A'>, <class 'B'>,

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 num
else: # code that depends on the try
print('Carry on!')
break

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

Opens a le and returns a corresponding le


p p g
object.

<file> = open('<path>', mode='r', encod

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) # M

<str/bytes> = <file>.readline() # R
<list> = <file>.readlines() # R
<file>.write(<str/bytes>) # W
<file>.writelines(<list>) # W

Methods do not add or strip trailing newlines.

Read Text from File

def read_file(filename):
with open(filename, encoding='utf-8
return file.readlines() # or re

for line in read_file(filename):


print(line)

Write Text to File

def write_to_file(filename, text):


with open(filename, 'w', encoding='
file.write(text)

Append Text to File

def append_to_file(filename, text):


with open(filename, 'a', encoding='
file.write(text)

Useful Libraries
CSV

import csv

Read Rows from CSV File

def read_csv_file(filename):
with open(filename, encoding='utf-8
return csv.reader(file, delimit

Write Rows to CSV File

def write_to_csv_file(filename, rows):


with open(filename, 'w', encoding='
writer = csv.writer(file, delim
writer.writerows(rows)

JSON

import json
<str> = json.dumps(<object>, ensure_
<object> = json.loads(<str>)

Read Object from JSON File


def read_json_file(filename):
with open(filename, encoding='utf-8
return json.load(file)

Write Object to JSON File

def write_to_json_file(filename, an_obj


with open(filename, 'w', encoding='
json.dump(an_object, file, ensu

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)

Write Object to File

def write_to_pickle_file(filename, an_o


with open(filename, 'wb') as file:
pickle.dump(an_object, file)

Pro le
Pro le

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,
from math import log, log10, log2
from math import inf, nan, isinf, isnan

Statistics

from statistics import mean, median, va

Random

from random import random, randint, cho


random() # random float between 0 and 1
randint(0, 100) # random integer betwee
random_el = choice([1,2,3,4]) # select
shuffle([1,2,3,4]) # shuffles a list

Datetime
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 de ned 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, dateti


from dateutil.tz import UTC, tzlocal, g

Constructors

<D> = date(year, month, day)


<T> = time(hour=0, minute=0, second=0,
<DT> = datetime(year, month, day, hour=
<TD> = timedelta(days=0, seconds=0, mic
minutes=0, hours=0, we

Use '<D/DT>.weekday()' to get the day


of the week (Mon == 0).

'fold=1' means second pass in case of


time jumping back for one hour.

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

<str> = <Match>.group() # Whole mat


<str> = <Match>.group(1) # Part in f

<tuple> = <Match>.groups() # All brack


<int> = <Match>.start() # Start ind
<int> = <Match>.end() # Exclusive

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

Credits

Inspired by: this repo

Quick The Company


Links Academy
About
Home Courses ZTM
Pricing Career Ambassador
Testimonials Paths Contact
Blog Career Us

You might also like