Python Cheat Sheet & Quick Reference
Python Cheat Sheet & Quick Reference
Python Cheat Sheet & Quick Reference
3k
Python
The Python cheat sheet is a one-page reference sheet for the Python 3 programming
language.
# Getting Started
Introduction
Python (python.org)
Hello World
Variables
dict Mapping
bool Boolean
Slicing String
See: Strings
Lists
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
See: Lists
If Else
num = 200
if num > 0:
print("num is greater than 0")
else:
print("num is not greater than 0")
:
See: Flow control
Loops
See: Loops
Functions
See: Functions
File Handling
Arithmetic
result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2 # => 1
result = 5 ** 3 # => 125
:
The / means quotient of x and y, and the // means floored quotient of x and y, also see
StackOverflow Get 10 Free Images From
Adobe Stock. Start Now.
Plus-Equals
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
See: Strings
Numbers
x = 1 # int
y = 2.8 # float
z = 1j # complex
>>> print(type(x))
<class 'int'>
Booleans
my_bool = True
my_bool = False
Lists
See: Lists
Tuple
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
Set
:
set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))
Dictionary
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4
- Casting
Integers
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Floats
Strings
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
heapq.heapify(myList)
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
Heaps are binary trees for which every parent node has a value less than or equal to any
of its children. Useful for accessing min/max value quickly. Time complexity: O(n) for
heapify, O(log n) push and pop. See: Heapq
q = deque() # empty
q = deque([1, 2, 3]) # with values
:
q.append(4) # append to right side
q.appendleft(0) # append to left side
print(q) # => deque([0, 1, 2, 3, 4])
Deque is a double-ended queue with O(1) time for append/pop operations from both
sides. Used as stacks and queues. See: Deque
# Python Strings
Array-like
Looping
Slicing string
┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
With a stride
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
:
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
String Length
Multiple copies
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
Check String
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
Concatenates
>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'
:
Formatting
name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))
format() Method
Input
Join
Endswith
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
F-Strings Others
F-Strings Sign
# Python Lists
Defining
>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Generate
Append
>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]
- List Slicing
a_list[start:end]
a_list[start:end:step]
Slicing
>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
With a stride
Remove
Concatenating
>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]
Count
>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2
Repeating
>>> li = ["re"] * 3
:
>>> li
['re', 're', 're']
num = 5
if num > 10:
print("num is totally bigger than 10.")
elif num < 10:
print("num is smaller than 10.")
else:
print("num is indeed 10.")
One line
>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a
else if
value = True
if not value:
print("Value is False")
elif value is None:
print("Value is None")
else:
print("Value is True")
:
# Python Loops
Basic
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
Prints: 2 3 5 7
With index
While
x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
Prints: 0 1 2 3
Break
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
Prints: 0 10 20 30 40
Continue
Prints: 30 40 60 70
Range
for i in range(4):
print(i) # Prints: 0 1 2 3
:
for i in range(4, 8):
print(i) # Prints: 4 5 6 7
With zip()
for/else
# Python Functions
Basic
def hello_world():
print('Hello, World!')
Return
:
def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y
add(5, 6) # => 11
Positional arguments
def varargs(*args):
return args
Keyword arguments
def keyword_args(**kwargs):
return kwargs
Returning multiple
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
Default Value
add(5) # => 15
add(5, 20) # => 25
:
Anonymous functions
# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)
# Python Modules
:
Import modules
import math
print(math.sqrt(16)) # => 4.0
From a module
Write a string
Read a string
- Object
Write an object
:
Write an object
Read an object
Delete a File
import os
os.remove("myfile.txt")
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")
Delete Folder
import os
os.rmdir("myfolder")
class MyNewClass:
pass
:
# Class Instantiation
my = MyNewClass()
Constructors
class Animal:
def __init__(self, voice):
self.voice = voice
cat = Animal('Meow')
print(cat.voice) # => Meow
dog = Animal('Woof')
print(dog.voice) # => Woof
Method
class Dog:
charlie = Dog()
charlie.bark() # => "Ham-Ham"
Class Variables
class MyClass:
class_variable = "A class variable!"
x = MyClass()
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# Calls the parent's print_test()
super().print_test()
repr() method
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # => John
User-defined exceptions
class CustomError(Exception):
pass
Polymorphism
class ParentClass:
def print_self(self):
print('A')
:
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
Overriding
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self() # => Child
Inheritance
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
:
# Miscellaneous
Comments
Generators
def double_numbers(iterable):
for i in iterable:
yield i + i
Generator to list
Handle exceptions
try:
# Use "raise" to raise an error
:
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do reco
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if
else: # Optional clause to the try/except block. Must f
print("All good!") # Runs only if the code in try raises no exceptio
finally: # Execute under all circumstances
print("We can clean up resources here")
Related Cheatsheet
Recent Cheatsheet