0% found this document useful (0 votes)
22 views14 pages

Python Cheat Sheet & Quick Reference

The document is a comprehensive Python cheat sheet that serves as a quick reference for various aspects of the Python 3 programming language, including data types, control flow, functions, file handling, and more. It provides examples of syntax and usage for lists, strings, dictionaries, and other data structures, as well as operations like arithmetic and string formatting. Additionally, it covers advanced topics such as f-strings, heaps, and deque operations.

Uploaded by

eunseo3929
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)
22 views14 pages

Python Cheat Sheet & Quick Reference

The document is a comprehensive Python cheat sheet that serves as a quick reference for various aspects of the Python 3 programming language, including data types, control flow, functions, file handling, and more. It provides examples of syntax and usage for lists, strings, dictionaries, and other data structures, as well as operations like arithmetic and string formatting. Additionally, it covers advanced topics such as f-strings, heaps, and deque operations.

Uploaded by

eunseo3929
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/ 14

int, float, complex Numeric

QuickRef.ME Stars 9.2k


list, tuple, range Sequence

dict Mapping

Python set, frozenset

bool
Set

Boolean
The Python cheat sheet is a one-page reference sheet for the Python 3 programming
language. bytes, bytearray, memoryview Binary

Slicing String

>>> msg = "Hello, World!"


>>> print(msg[2:5])
llo

# Getting Started See: Strings


Introduction

Lists
Python (python.org)
mylist = []
Learn X in Y minutes (learnxinyminutes.com)
mylist.append(1)
Regex in python (quickref.me) mylist.append(2)
for item in mylist:
print(item) # prints out 1,2
Hello World

See: Lists
>>> print("Hello, World!")
Hello, World!
If Else

The famous "Hello World" program in Python


num = 200
if num > 0:
Variables print("num is greater than 0")
else:
age = 18 # age is of type int
print("num is not greater than 0")
name = "John" # name is now of type str
print(name)
See: Flow control

Python can't declare a variable without assignment.


Loops

Data Types for item in range(6):


str Text if item == 3: break
print(item)
else: # P t 1 P t 2
print("Finally finished!") f-Strings (Python 3.6+)

>>> website = 'Quickref.ME'


S L
>>> f"Hello, {website}"
Functions
"Hello, Quickref.ME"
>>> def my_function():
... print("Hello from a function") >>> num = 10
... >>> f'{num} + 10 = {num + 10}'
>>> my_function() '10 + 10 = 20'
Hello from a function
See: Python F-Strings
See: Functions

File Handling

with open("myfile.txt", "r", encoding='utf8') as file:


for line in file:
print(line) # Python Built-in Data Types
Strings

See: File Handling


hello = "Hello World"
hello = 'Hello World'
Arithmetic

multi_string = """Multiline Strings


result = 10 + 30 # => 40
Lorem ipsum dolor sit amet,
result = 40 - 10 # => 30
consectetur adipiscing elit """
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division) See: Strings
result = 25 % 2 # => 1
result = 5 ** 3 # => 125 Numbers

x = 1 # int
The / means quotient of x and y, and the // means floored quotient of x and y, also see
y = 2.8 # float
StackOverflow
z = 1j # complex

Plus-Equals
>>> print(type(x))
<class 'int'>
counter = 0
counter += 10 # => 10
counter = 0 Booleans
counter = counter + 10 # => 10
my_bool = True
message = "Part 1." my_bool = False
Lists x = int(1) # x will be 1
y = int(2.8) # y will be 2
list1 = ["apple", "banana", "cherry"] z = int("3") # z will be 3
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3] Floats
list4 = list((1, 5, 7, 9, 3))
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
See: Lists
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Tuple

Strings
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
Similar to List but immutable

Set

set1 = {"a", "b", "c"}


set2 = set(("a", "b", "c")) # Python Advanced Data Types
Set of unique items/objects

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

Key: Value pair, JSON like object

- Casting

Integers
Heaps
Deque is a double-ended queue with O(1) time for append/pop operations from both sides.
import heapq

myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # turn myList into a Min Heap

# Python Strings
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # first value is always the smallest in the heap
Array-like
heapq.heappush(myList, 10) # insert 10
x = heapq.heappop(myList) # pop and return smallest item >>> hello = "Hello, World"
print(x) # => 1 >>> print(hello[1])
e
Negate all values to use Min Heap as Max Heap >>> print(hello[-1])
d
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # multiply by -1 to negate
Get the character at position 1 or last
heapq.heapify(myList)

Looping
x = heapq.heappop(myList)
print(-x) # => 9 (making sure to multiply by -1 again)
>>> for char in "foo":
... print(char)
Heaps are binary trees for which every parent node has a value less than or equal to any of its f
children. Useful for accessing min/max value quickly. Time complexity: O(n) for heapify, O(log n) o
push and pop. See: Heapq o

Stacks and Queues Loop through the letters in the word "foo"

from collections import deque


Slicing string

q = deque() # empty
┌───┬───┬───┬───┬───┬───┬───┐
q = deque([1, 2, 3]) # with values
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
q.append(4) # append to right side
0 1 2 3 4 5 6 7
q.appendleft(0) # append to left side
-7 -6 -5 -4 -3 -2 -1
print(q) # => deque([0, 1, 2, 3, 4])

x = q.pop() # remove & return from right >>> s = 'mybacon'


y = q.popleft() # remove & return from left >>> s[2:5]
print(x) # => 4 'bac'
print(y) # => 0 >>> s[0:2]
print(q) # => deque([1, 2, 3]) 'my'

q.rotate(1) # rotate 1 step to the right


>>> s = 'mybacon'
print(q) # => deque([3, 1, 2])
>>> s[:2]
'my'
>>> s[2:] >>> s not in 'I saw The Holy Grail!'
'bacon' True
>>> s[:2] + s[2:]
'mybacon'
>>> s[:] Concatenates
'mybacon'
>>> s = 'spam'
>>> t = 'egg'
>>> s = 'mybacon'
>>> s + t
>>> s[-5:-1]
'spamegg'
'baco'
>>> 'spam' 'egg'
>>> s[2:6]
'spamegg'
'baco'

With a stride Formatting

>>> s = '12345' * 5 name = "John"


>>> s print("Hello, %s!" % name)
'1234512345123451234512345'
>>> s[::5]
name = "John"
'11111'
age = 23
>>> s[4::5]
print("%s is %d years old." % (name, age))
'55555'
>>> s[::-5]
format() Method
'55555'
>>> s[::-1] txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
'5432154321543215432154321' txt2 = "My name is {0}, I'm {1}".format("John", 36)
String Length txt3 = "My name is {}, I'm {}".format("John", 36)

>>> hello = "Hello, World!"


Input
>>> print(len(hello))
13 >>> name = input("Enter your name: ")
Enter your name: Tom
The len() function returns the length of a string >>> name
'Tom'
Multiple copies
Get input data from console
>>> s = '===+'
>>> n = 8
Join
>>> s * n
'===+===+===+===+===+===+===+===+' >>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'
Check String

Endswith
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
f-Strings Type

>>> f'{10:b}' # binary type


'1010'
>>> f'{10:o}' # octal type

# Python F-Strings (Since Python 3.6+) '12'


>>> f'{200:x}' # hexadecimal type
f-Strings usage 'c8'
>>> f'{200:X}'
>>> website = 'Quickref.ME' 'C8'
>>> f"Hello, {website}" >>> f'{345600000000:e}' # scientific notation
"Hello, Quickref.ME" '3.456000e+11'
>>> f'{65:c}' # character type
>>> num = 10 'A'
>>> f'{num} + 10 = {num + 10}' >>> f'{10:#b}' # [type] with notation (base)
'10 + 10 = 20' '0b1010'
>>> f'{10:#o}'
>>> f"""He said {"I'm John"}""" '0o12'
"He said I'm John" >>> f'{10:#x}'
'0xa'
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}' F-Strings Others

'{5} stars'
>>> f'{-12345:0=10}' # negative numbers
'-000012345'
>>> name = 'Eric'
>>> f'{12345:010}' # [0] shortcut (no align)
>>> age = 27
'0000012345'
>>> f"""Hello!
>>> f'{-12345:010}'
... I'm {name}.
'-000012345'
... I'm {age}."""
>>> import math # [.precision]
"Hello!\n I'm Eric.\n I'm 27."
>>> math.pi
3.141592653589793
it is available since Python 3.6, also see: Formatted string literals >>> f'{math.pi:.2f}'
'3.14'
f-Strings Fill Align >>> f'{1000000:,.2f}' # [grouping_option]
'1,000,000.00'
>>> f'{"text":10}' # [width] >>> f'{1000000:_.2f}'
'text ' '1_000_000.00'
>>> f'{"test":*>10}' # fill left >>> f'{0.25:0%}' # percentage
'******test' '25.000000%'
>>> f'{"test":*<10}' # fill right >>> f'{0.25:.0%}'
'test******' '25%'
>>> f'{"test":*^10}' # fill center
'***test***'
F-Strings Sign
>>> f'{12345:+}' # [sign] (+/-) >>> li = []
'+12345' >>> li.append(1)
>>> f'{-12345:+}' >>> li
'-12345' [1]
>>> f'{-12345:+10}' >>> li.append(2)
' -12345' >>> li
>>> f'{-12345:+010}' [1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)

# Python Lists - List Slicing

Defining Syntax of list slicing:

>>> li1 = []
a_list[start:end]
>>> li1
a_list[start:end:step]
[]
>>> li2 = [4, 5, 6]
Slicing
>>> li2
[4, 5, 6]
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> li3 = list((1, 2, 3))
>>> a[2:5]
>>> li3 ['bacon', 'tomato', 'ham']
[1, 2, 3] >>> a[-5:-2]
>>> li4 = list(range(1, 11))
['egg', 'bacon', 'tomato']
>>> li4
>>> a[1:4]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
['egg', 'bacon', 'tomato']

Generate Omitting index

>>> list(filter(lambda x : x % 2 == 1, range(1, 20))) >>> a[:4]


[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] ['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
>>> [x ** 2 for x in range (1, 11) if x % 2 == 1] ['spam', 'egg', 'bacon', 'tomato']
[1, 9, 25, 49, 81] >>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> [x for x in [3, 4, 5, 6, 7] if x > 5] >>> a[2:len(a)]
[6, 7] ['bacon', 'tomato', 'ham', 'lobster']
>>> a
>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
[6, 7] >>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

Append
With a stride
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster'] >>> li = [3, 1, 3, 2, 5]
>>> a[0:6:2] >>> li.sort()
['spam', 'bacon', 'ham'] >>> li
>>> a[1:6:2] [1, 2, 3, 3, 5]
['egg', 'tomato', 'lobster'] >>> li.reverse()
>>> a[6:0:-2] >>> li
['lobster', 'tomato', 'egg'] [5 3 3 2 1]
>>> a Count
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1] >>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
Remove
2
>>> li = ['bread', 'butter', 'milk']
>>> li.pop() Repeating
'milk'
>>> li >>> li = ["re"] * 3
['bread', 'butter'] >>> li
>>> del li[0] ['re', 're', 're']
>>> li
['butter']

Access

# Python Flow control


>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a' Basic
>>> li[-1]
'd' num = 5
>>> li[4] if num > 10:
Traceback (most recent call last): print("num is totally bigger than 10.")
File "<stdin>", line 1, in <module> elif num < 10:
IndexError: list index out of range print("num is smaller than 10.")
else:
print("num is indeed 10.")
Concatenating

>>> odd = [1, 3, 5] One line


>>> odd.extend([9, 11, 13])
>>> odd >>> a = 330
[1, 3, 5, 9, 11, 13] >>> b = 200
>>> odd = [1, 3, 5] >>> r = "a" if a > b else "b"
>>> odd + [9, 11, 13] >>> print(r)
[1, 3, 5, 9, 11, 13] a

Sort & Reverse else if


break
value = True print(x)
if not value:
print("Value is False")
Prints: 0 10 20 30 40
elif value is None:
print("Value is None") Continue
else:
print("Value is True") for index in range(3, 8):
x = index * 10
if index == 5:
continue
print(x)

# Python Loops Prints: 30 40 60 70


Basic

Range
primes = [2, 3, 5, 7]
for prime in primes: for i in range(4):
print(prime) print(i) # Prints: 0 1 2 3

Prints: 2 3 5 7 for i in range(4, 8):


print(i) # Prints: 4 5 6 7

With index
for i in range(4, 10, 2):
animals = ["dog", "cat", "mouse"] print(i) # Prints: 4 6 8
# enumerate() adds counter to an iterable
for i, value in enumerate(animals):
With zip()
print(i, value)
words = ['Mon', 'Tue', 'Wed']
Prints: 0 dog 1 cat 2 mouse nums = [1, 2, 3]
# Use zip to pack into a tuple list
for w, n in zip(words, nums):
While
print('%d:%s, ' %(n, w))
x = 0
while x < 4: Prints: 1:Mon, 2:Tue, 3:Wed,
print(x)
x += 1 # Shorthand for x = x + 1
for/else

Prints: 0 1 2 3 nums = [60, 70, 30, 110, 90]


for n in nums:
if n > 100:
Break
print("%d is bigger than 100" %n)
x = 0 break
for index in range(10): else:
x = index * 10 print("Not found!")
if index == 5:
Al P th Ti def add(x, y=10):
return x + y

add(5) # => 15
add(5, 20) # => 25

# Python Functions Anonymous functions


Basic
# => True
def hello_world(): (lambda x: x > 2)(3)
print('Hello, World!')
# => 5
Return (lambda x, y: x ** 2 + y ** 2)(2, 1)

def add(x, y):


print("x is %s, y is %s" %(x, y))
return x + y

add(5, 6) # => 11
# Python Modules
Positional arguments Import modules

def varargs(*args): import math


return args print(math.sqrt(16)) # => 4.0

varargs(1, 2, 3) # => (1, 2, 3)


From a module

Keyword arguments
from math import ceil, floor
print(ceil(3.7)) # => 4.0
def keyword_args(**kwargs): print(floor(3.7)) # => 3.0
return kwargs

Import all
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness") from math import *

Returning multiple Shorten module

def swap(x, y): import math as m


return y, x
# => True
x = 1 math.sqrt(16) == m.sqrt(16)
y = 2
x, y = swap(x, y) # => x = 2, y = 1
Functions and attributes

Default Value
import math Delete a File

import os
os.remove("myfile.txt")

# Python File Handling Check and Delete

- Read file import os


Line by line if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
with open("myfile.txt") as file: else:
for line in file: print("The file does not exist")
print(line)

Delete Folder
With line number
import os
file = open('myfile.txt', 'r') os.rmdir("myfolder")
for i, line in enumerate(file, start=1):
print("Number %s: %s" % (i, line))

- String

Write a string

contents = {"aa": 12, "bb": 21} # Python Classes & Inheritance


with open("myfile1.txt", "w+") as file: Defining
file.write(str(contents))
class MyNewClass:
Read a string pass

with open('myfile1.txt', "r+") as file: # Class Instantiation


contents = file.read() my = MyNewClass()
print(contents)

Constructors
- Object
class Animal:
Write an object
def __init__(self, voice):
contents = {"aa": 12, "bb": 21} self.voice = voice
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents)) cat = Animal('Meow')
print(cat.voice) # => Meow
Read an object
dog = Animal('Woof')
with open('myfile2.txt', "r+") as file: print(dog.voice) # => Woof
contents = json.load(file)

Method
def __repr__(self):
class Dog: return self.name

# Method of the class john = Employee('John')


def bark(self): print(john) # => John
print("Ham-Ham")

User-defined exceptions
charlie = Dog()
charlie.bark() # => "Ham-Ham" class CustomError(Exception):
pass
Class Variables

Polymorphism
class MyClass:
class_variable = "A class variable!" class ParentClass:
def print_self(self):
# => A class variable! print('A')
print(MyClass.class_variable)
class ChildClass(ParentClass):
x = MyClass() def print_self(self):
print('B')
# => A class variable!
print(x.class_variable) obj_A = ParentClass()
obj_B = ChildClass()
Super() Function
obj_A.print_self() # => A
class ParentClass: obj_B.print_self() # => B
def print_test(self):
print("Parent Method")
Overriding

class ChildClass(ParentClass): class ParentClass:


def print_test(self): def print_self(self):
print("Child Method") print("Parent")
# Calls the parent's print_test()
super().print_test() class ChildClass(ParentClass):
def print_self(self):
>>> child_instance = ChildClass() print("Child")
>>> child_instance.print_test()
Child Method child_instance = ChildClass()
Parent Method child_instance.print_self() # => Child

Inheritance
repr() method

class Employee: class Animal:


def __init__(self, name): def __init__(self, name, legs):
self.name = name self.name = name
self.legs = legs
Comments
class Dog(Animal):
def sound(self): # This is a single line comments.
print("Woof!")
""" Multiline strings can be written
Yoki = Dog("Yoki", 4) using three "s, and are often used
print(Yoki.name) # => YOKI as documentation.
print(Yoki.legs) # => 4 """
Yoki.sound() # => Woof!

''' Multiline strings can be written


using three 's, and are often used
as documentation.
'''

# Miscellaneous
Generators

def double_numbers(iterable):
for i in iterable:
yield i + i

Generators help you make lazy code.

Generator to list

values = (-x for x in [1,2,3,4,5])


gen_to_list = list(values)

# => [-1, -2, -3, -4, -5]


print(gen_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 recovery her
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if require
else: # Optional clause to the try/except block. Must follow al
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
 
Related Cheatsheet

Awk Cheatsheet Bash Cheatsheet


Quick Reference Quick Reference

Recent Cheatsheet

Remote Work Revolution Cheatsheet Homebrew Cheatsheet


Quick Reference Quick Reference

PyTorch Cheatsheet Taskset Cheatsheet


Quick Reference Quick Reference

© 2025 QuickRef.ME, All rights reserved.

You might also like