Open menu Skip to content Contact Us Send feedback, report a content error, or ask for help with your account.
© 2026 PariksaHub. All rights reserved.
Python Cheatsheet | PariksaHub
Python Cheatsheet Comprehensive Python programming reference guide covering syntax, data structures, functions, OOP, and more. Essential Python commands and examples for quick reference.
Programming
basics data-structures functions io oop text-processing advanced
s
[
0
:
5
]
# 'Hello'
s
[
:
:
-
1
]
# 'dlroW olleH'
# String methods
s
.
upper
(
)
# 'HELLO WORLD'
s
.
lower
(
)
# 'hello world'
s
.
replace
(
"H"
,
"J"
)
# 'Jello World'
s
.
split
(
)
# ['Hello', 'World']
s
.
strip
(
)
# Removes whitespace
# String formatting
name
=
"John"
f"Hello
{
name
}
"
# f-string (Python 3.6+)
"Hello {}"
.
format
(
name
)
# format method
# [1, 2, 3, 4, 5, 6]
my_list
.
insert
(
0
,
0
)
# [0, 1, 2, 3, 4, 5, 6]
my_list
.
pop
(
)
# Removes and returns 6
my_list
.
remove
(
0
)
# Removes first 0
my_list
.
sort
(
)
# Sorts in place
my_list
.
reverse
(
)
# Reverses in place
# List slicing
my_list
[
1
:
3
]
# [2, 3]
my_list
[
:
3
]
# [1, 2, 3]
my_list
[
2
:
]
# [3, 4, 5]
# List comprehensions
squares
=
[
x
**
2
for
x
in
range
(
10
)
]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_squares
=
[
x
**
2
for
x
in
range
(
10
)
if
x
%
2
==
0
]
# [0, 4, 16, 36, 64]
nested
=
[
[
x
*
y
for
y
in
range
(
3
)
]
for
x
in
range
(
3
)
]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
}
# Accessing values
person
[
"name"
]
# 'John'
person
.
get
(
"name"
)
# 'John' (safer)
person
.
get
(
"email"
,
"N/A"
)
# Returns default if key missing
# Modifying
person
[
"age"
]
=
31
person
[
"email"
]
=
"john@example.com"
# Add new key
person
.
pop
(
"email"
)
# Remove and return value
del
person
[
"city"
]
# Remove key
# Dictionary methods
person
.
keys
(
)
# dict_keys(['name', 'age'])
person
.
values
(
)
# dict_values(['John', 31])
person
.
items
(
)
# dict_items([('name', 'John'), ...])
# Dictionary comprehension
squares_dict
=
{
x
:
x
**
2
for
x
in
range
(
5
)
}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
z
=
tuple1
# Unpacking
# Tuple methods
my_tuple
=
(
1
,
2
,
2
,
3
)
my_tuple
.
count
(
2
)
# 2
my_tuple
.
index
(
3
)
# 3
# Sets (unordered, unique elements)
my_set
=
{
1
,
2
,
3
,
4
}
my_set
.
add
(
5
)
# Add element
my_set
.
remove
(
2
)
# Remove (raises KeyError if missing)
my_set
.
discard
(
2
)
# Remove (no error if missing)
# Set operations
set1
=
{
1
,
2
,
3
}
set2
=
{
3
,
4
,
5
}
set1
|
set2
# Union: {1, 2, 3, 4, 5}
set1
&
set2
# Intersection: {3}
set1
-
set2
# Difference: {1, 2}
set1
^
set2
# Symmetric difference: {1, 2, 4, 5}
print
(
"Adult"
)
else
:
print
(
"Senior"
)
# Ternary operator
status
=
"adult"
if
age
>=
18
else
"minor"
# For loops
for
i
in
range
(
5
)
:
print
(
i
)
# 0, 1, 2, 3, 4
for
item
in
[
1
,
2
,
3
]
:
print
(
item
)
# Enumerate
for
index
,
value
in
enumerate
(
[
"a"
,
"b"
,
"c"
]
)
:
print
(
index
,
value
)
# 0 a, 1 b, 2 c
# While loop
count
=
0
while
count
<
5
:
print
(
count
)
count
+=
1
if
count
==
3
:
break
# Exit loop
if
count
==
2
:
continue
# Skip rest of iteration
power
(
base
,
exponent
=
2
)
:
return
base
**
exponent
power
(
3
)
# 9
power
(
3
,
3
)
# 27
# *args and **kwargs
def
func
(
*
args
,
**
kwargs
)
:
print
(
args
)
# Tuple of positional args
print
(
kwargs
)
# Dict of keyword args
func
(
1
,
2
,
3
,
name
=
"John"
,
age
=
30
)
# Lambda functions
square
=
lambda
x
:
x
**
2
add
=
lambda
x
,
y
:
x
+
y
# Map, filter, reduce
numbers
=
[
1
,
2
,
3
,
4
,
5
]
map
(
lambda
x
:
x
**
2
,
numbers
)
# Map
filter
(
lambda
x
:
x
%
2
==
0
,
numbers
)
# Filter
from
functools
import
reduce
reduce
(
lambda
x
,
y
:
x
+
y
,
numbers
)
# Reduce
# Function annotations (type hints)
def
add
(
a
:
int
,
b
:
int
)
-
>
int
:
return
a
+
b
for
line
in
f
:
# Iterate line by line
print
(
line
)
# Writing files
with
open
(
"file.txt"
,
"w"
)
as
f
:
f
.
write
(
"Hello World"
)
f
.
writelines
(
[
"Line 1\n"
,
"Line 2\n"
]
)
# Appending
with
open
(
"file.txt"
,
"a"
)
as
f
:
f
.
write
(
"New line"
)
# File modes
# "r" - read (default)
# "w" - write (overwrites)
# "a" - append
# "x" - exclusive creation
# "b" - binary mode
# "t" - text mode (default)
# JSON files
import
json
with
open
(
"data.json"
,
"r"
)
as
f
:
data
=
json
.
load
(
f
)
with
open
(
"data.json"
,
"w"
)
as
f
:
json
.
dump
(
data
,
f
,
indent
=
2
)
def
__init__
(
self
,
name
,
age
)
:
self
.
name
=
name
# Instance attribute
self
.
age
=
age
# Instance method
def
introduce
(
self
)
:
return
f"I'm
{
self
.
name
}
,
{
self
.
age
}
years old"
# Class method
@classmethod
def
from_birth_year
(
cls
,
name
,
birth_year
)
:
age
=
2024
-
birth_year
return
cls
(
name
,
age
)
# Static method
@staticmethod
def
is_adult
(
age
)
:
return
age
>=
18
# Inheritance
class
Student
(
Person
)
:
def
__init__
(
self
,
name
,
age
,
student_id
)
:
super
(
)
.
__init__
(
name
,
age
)
self
.
student_id
=
student_id
def
study
(
self
)
:
return
f"
{
self
.
name
}
is studying"
# Special methods (dunder methods)
class
Vector
:
def
__init__
(
self
,
x
,
y
)
:
self
.
x
=
x
self
.
y
=
y
def
__add__
(
self
,
other
)
:
return
Vector
(
self
.
x
+
other
.
x
,
self
.
y
+
other
.
y
)
def
__str__
(
self
)
:
return
f"Vector(
{
self
.
x
}
,
{
self
.
y
}
)"
def
__repr__
(
self
)
:
return
f"Vector(
{
self
.
x
}
,
{
self
.
y
}
)"
try
:
value
=
int
(
"abc"
)
result
=
10
/
value
except
ValueError
:
print
(
"Invalid number"
)
except
ZeroDivisionError
:
print
(
"Cannot divide by zero"
)
except
Exception
as
e
:
print
(
f"Error:
{
e
}
"
)
# Else and finally
try
:
file
=
open
(
"file.txt"
)
data
=
file
.
read
(
)
except
FileNotFoundError
:
print
(
"File not found"
)
else
:
print
(
"File read successfully"
)
finally
:
file
.
close
(
)
# Always executes
# Raising exceptions
if
age
<
0
:
raise
ValueError
(
"Age cannot be negative"
)
# Custom exceptions
class
CustomError
(
Exception
)
:
pass
raise
CustomError
(
"Something went wrong"
)
# Exception chaining
try
:
process_data
(
)
except
ValueError
as
e
:
raise
RuntimeError
(
"Processing failed"
)
from
e
if
match
:
print
(
match
.
group
(
)
)
# "100"
# Common patterns
re
.
findall
(
r"\d+"
,
text
)
# Find all: ["100"]
re
.
sub
(
r"\d+"
,
"X"
,
text
)
# Replace: "Price is X dollars"
re
.
split
(
r"\s+"
,
text
)
# Split: ["Price", "is", "100", "dollars"]
# Pattern flags
re
.
search
(
r"hello"
,
text
,
re
.
IGNORECASE
)
re
.
search
(
r"^start"
,
text
,
re
.
MULTILINE
)
# Groups
pattern
=
r"(\d{3})-(\d{3})-(\d{4})"
phone
=
"123-456-7890"
match
=
re
.
search
(
pattern
,
phone
)
match
.
group
(
1
)
# "123"
match
.
groups
(
)
# ("123", "456", "7890")
# Named groups
pattern
=
r"(?P<area>\d{3})-(?P<exchange>\d{3})"
match
=
re
.
search
(
pattern
,
phone
)
match
.
group
(
"area"
)
# "123"
num
in
countdown
(
5
)
:
print
(
num
)
# 5, 4, 3, 2, 1
# Generator expression
squares
=
(
x
**
2
for
x
in
range
(
10
)
)
next
(
squares
)
# 0
next
(
squares
)
# 1
# Iterator protocol
class
Counter
:
def
__init__
(
self
,
low
,
high
)
:
self
.
low
=
low
self
.
high
=
high
def
__iter__
(
self
)
:
return
self
def
__next__
(
self
)
:
if
self
.
low
>
self
.
high
:
raise
StopIteration
self
.
low
+=
1
return
self
.
low
-
1
for
num
in
Counter
(
1
,
5
)
:
print
(
num
)
# 1, 2, 3, 4, 5
)
print
(
"After function call"
)
return
wrapper
@my_decorator
def
say_hello
(
)
:
print
(
"Hello!"
)
say_hello
(
)
# Output:
# Before function call
# Hello!
# After function call
# Decorator with arguments
def
repeat
(
times
)
:
def
decorator
(
func
)
:
def
wrapper
(
*
args
,
**
kwargs
)
:
for
_
in
range
(
times
)
:
result
=
func
(
*
args
,
**
kwargs
)
return
result
return
wrapper
return
decorator
@repeat
(
3
)
def
greet
(
name
)
:
print
(
f"Hello,
{
name
}
"
)
# Built-in decorators
class
MyClass
:
@property
def
name
(
self
)
:
return
self
.
_name
@name
.
setter
def
name
(
self
,
value
)
:
self
.
_name
=
value
@staticmethod
def
static_method
(
)
:
return
"Static"
@classmethod
def
class_method
(
cls
)
:
return
cls
extend
(
[
5
,
6
]
)
# [1, 2, 3, 4, 5, 6]
my_list
.
insert
(
0
,
0
)
# [0, 1, 2, 3, 4, 5, 6]
# Removing elements
my_list
.
remove
(
0
)
# Remove first occurrence
my_list
.
pop
(
)
# Remove and return last
my_list
.
pop
(
0
)
# Remove at index
my_list
.
clear
(
)
# Empty the list
# Finding elements
my_list
.
index
(
3
)
# Returns index of first occurrence
my_list
.
count
(
2
)
# Count occurrences
3
in
my_list
# True
# Sorting and reversing
my_list
.
sort
(
)
# Sort in place
my_list
.
sort
(
reverse
=
True
)
# Descending
sorted
(
my_list
)
# Returns new sorted list
my_list
.
reverse
(
)
# Reverse in place
reversed
(
my_list
)
# Returns iterator
# List concatenation
list1
+
list2
# Concatenate
list1
*
3
# Repeat list 3 times
=
d
[
"a"
]
# Get value (KeyError if missing)
value
=
d
.
get
(
"a"
)
# Safe get (None if missing)
value
=
d
.
get
(
"a"
,
0
)
# With default
value
=
d
.
setdefault
(
"d"
,
4
)
# Set if missing, return value
# Updating
d
.
update
(
{
"e"
:
5
}
)
# Merge dictionaries
d
|
=
{
"f"
:
6
}
# Python 3.9+ merge operator
# Removing
del
d
[
"a"
]
# Remove key
d
.
pop
(
"b"
)
# Remove and return value
d
.
popitem
(
)
# Remove and return (key, value)
d
.
clear
(
)
# Empty dictionary
# Views (Python 3)
d
.
keys
(
)
# dict_keys view
d
.
values
(
)
# dict_values view
d
.
items
(
)
# dict_items view
# Dictionary methods
len
(
d
)
# Number of keys
"a"
in
d
# Check key existence
# Copying
d2
=
d
.
copy
(
)
# Shallow copy
d3
=
dict
(
d
)
# Shallow copy
from
copy
import
deepcopy
d4
=
deepcopy
(
d
)
# Deep copy
5
}
"
# 'Age: 35'
f"
{
name
:
>10
}
"
# Right align
f"
{
name
:
<10
}
"
# Left align
f"
{
age
:
05d
}
"
# Zero-padded: '00030'
f"
{
3.14159
:
.2f
}
"
# 2 decimals: '3.14'
# .format() method
"Hello, {}"
.
format
(
name
)
"Hello, {name}"
.
format
(
name
=
name
)
"{0} is {1}"
.
format
(
name
,
age
)
"{name:>10}"
.
format
(
name
=
name
)
# % formatting (old style)
"Hello, %s"
%
name
"%s is %d"
%
(
name
,
age
)
# Template strings
from
string
import
Template
t
=
Template
(
"Hello, $name"
)
t
.
substitute
(
name
=
name
)
birthday
=
date
(
1990
,
5
,
15
)
meeting
=
datetime
(
2024
,
12
,
25
,
14
,
30
)
# Formatting
now
.
strftime
(
"%Y-%m-%d %H:%M:%S"
)
# "2024-12-20 14:30:00"
datetime
.
strptime
(
"2024-12-20"
,
"%Y-%m-%d"
)
# Time delta
future
=
now
+
timedelta
(
days
=
7
)
past
=
now
-
timedelta
(
hours
=
24
)
difference
=
future
-
now
# Returns timedelta
print
(
difference
.
days
)
# 7
print
(
difference
.
seconds
)
# Seconds component
# Timezone (Python 3.2+)
from
datetime
import
timezone
dt
=
datetime
.
now
(
timezone
.
utc
)
# Using pytz (third-party)
import
pytz
tz
=
pytz
.
timezone
(
"US/Eastern"
)
dt_eastern
=
datetime
.
now
(
tz
)