Python Cheat Sheet

Data Types dynamic
# Numeric: int, float, complex
# Boolean: bool
# Sequence: str, list, tuple
# Set: set, frozenset
# Mapping: dict
# None: NoneType
# Binary: bytes, bytearray, memoryview
# Checking: type()
CategoryData TypeExample
Numericint10
float3.14
complex2+3j
BooleanboolTrue
Sequencestr"Hello"
list[1, 2, 3]
tuple(1, 2, 3)
Setset{1, 2, 3}
frozensetfrozenset([1,2,3])
Mappingdict{"a": 1}
NoneNoneTypeNone
Binarybytesb"ABC"
bytearraybytearray(5)
memoryviewmemoryview(b"ABC")
Checkingtype()print(type(10)) β†’ <class 'int'>
Complete Data Type Summary
CategoryTypeExample
Numericint, float, complex10, 3.14, 2+3j
BooleanboolTrue / False
Sequencestr, list, tuple"Hello", [1,2,3], (1,2,3)
Setset, frozenset{1,2,3}, frozenset([1,2,3])
Mappingdict{"a":1}
NoneNoneTypeNone
Binarybytes, bytearray, memoryviewb"ABC", bytearray(5), memoryview(b"ABC")
Checkingtype()type(10) β†’ <class 'int'>

Tip: Python is dynamically typed β€” no need to declare type before assignment. Use type() or isinstance() to check types at runtime.

Collection Data Types
FeatureListTupleSetDictionary
Symbol[](){}{key:value}
MutableYesNoYesYes
Insertion orderPreservedPreservedNot preservedPreserved
DuplicatesAllowedAllowedNot allowedKeys ❌ / Values βœ…
HeterogeneousAllowedAllowedAllowedAllowed
IndexingYesYesNoBy keys
Empty creation[]()set(){}
# Examples
my_list = [1, 2, "hello", 3.14]
my_list.append(5)          # modify

my_tuple = (1, 2, "hello", 3.14)
# my_tuple[0] = 5          # ERROR! immutable

my_set = {1, 2, 3, 3}      # {1, 2, 3}
my_set.add(4)

my_dict = {"name": "Alice", "age": 25}
my_dict["city"] = "NYC"
Quick Guide: Which Collection to Use?
NeedUseWhy
Ordered + mutablelistCan add/remove/change items
Ordered + immutabletupleSafe from changes, faster
Unique items onlysetAuto-removes duplicates
Key-value pairsdictFast lookups by key

Note: Tuples can be used as dictionary keys (if they contain only immutable items), but lists cannot.

Common Built-in Functions
FunctionDescriptionExampleOutput
type()Returns data typetype(10)<class 'int'>
len()Returns lengthlen("hello")5
id()Memory addressid("test")unique ID
str()Convert to stringstr(123)'123'
int()Convert to integerint("45")45
float()Convert to floatfloat("3.14")3.14
bool()Convert to booleanbool(0)False
list()Convert to listlist((1,2,3))[1, 2, 3]
tuple()Convert to tupletuple([1,2,3])(1, 2, 3)
set()Convert to setset([1,1,2]){1, 2}
dict()Create dictionarydict([("a",1),("b",2)]){'a':1,'b':2}
sorted()Returns sorted listsorted([3,1,2])[1, 2, 3]
min()Minimummin([5,2,8])2
max()Maximummax([5,2,8])8
sum()Sumsum([1,2,3])6
abs()Absolute valueabs(-10)10
round()Rounds numberround(3.14159, 2)3.14
isinstance()Checks typeisinstance(10, int)True
hash()Returns hash valuehash("hello")integer
Complete Python Built-in Functions

len(), type(), id(), str(), int(), float(), bool(), list(), tuple(), set(), dict(), sorted(), min(), max(), sum(), abs(), round(), isinstance(), hash(), callable(), chr(), ord(), bin(), oct(), hex(), dir(), help(), eval(), exec(), input(), print(), open(), range(), enumerate(), zip(), filter(), map(), reversed(), slice(), iter(), next(), any(), all(), delattr(), getattr(), setattr(), hasattr(), globals(), locals(), vars(), __import__(), compile(), memoryview(), property(), staticmethod(), classmethod(), super(), repr(), ascii(), format(), frozenset(), bytearray(), bytes()

Most used: len(), type(), range(), print(), input(), enumerate(), zip(), sorted(), map(), filter()

String Methods
MethodDescriptionExampleOutput
.upper()Uppercase"hello".upper()'HELLO'
.lower()Lowercase"HELLO".lower()'hello'
.capitalize()First char uppercase"hello".capitalize()'Hello'
.title()Each word capitalized"hello world".title()'Hello World'
.strip()Removes whitespace" hi ".strip()'hi'
.replace()Replaces substring"hello".replace("l","x")'hexxo'
.split()Splits into list"a,b,c".split(",")['a','b','c']
.join()Joins iterable",".join(['a','b','c'])'a,b,c'
.find()Finds substring index"hello".find("e")1
.count()Counts occurrences"hello".count("l")2
.startswith()Checks start"hello".startswith("he")True
.endswith()Checks end"hello".endswith("lo")True
.isdigit()All digits?"123".isdigit()True
.isalpha()All alphabets?"abc".isalpha()True
.zfill()Pads with zeros"42".zfill(5)'00042'
.format()Formats string"{} world".format("Hello")'Hello world'
.center()Centers string"hi".center(10,"*")'****hi****'
.ljust()Left justifies"hi".ljust(10,"-")'hi--------'
.rjust()Right justifies"hi".rjust(10,"-")'--------hi'
Complete String Methods List

.upper(), .lower(), .strip(), .split(), .join(), .rstrip(), .lstrip(), .capitalize(), .title(), .replace(), .find(), .index(), .count(), .startswith(), .endswith(), .isdigit(), .isalpha(), .isalnum(), .islower(), .isupper(), .zfill(), .format(), .center(), .ljust(), .rjust(), .partition(), .rpartition(), .splitlines(), .swapcase(), .casefold(), .encode(), .expandtabs(), .isdecimal(), .isidentifier(), .isnumeric(), .isprintable(), .isspace(), .maketrans(), .translate(), .rsplit(), .rfind(), .rindex(), .format_map()

Most used: .upper(), .lower(), .strip(), .split(), .join(), .replace()

List Methods
MethodDescriptionExampleOutput
.append()Adds element to endlst=[1,2]; lst.append(3)[1,2,3]
.extend()Adds multiplelst=[1,2]; lst.extend([3,4])[1,2,3,4]
.insert()Inserts at indexlst=[1,3]; lst.insert(1,2)[1,2,3]
.remove()Removes first occurrencelst=[1,2,3,2]; lst.remove(2)[1,3,2]
.pop()Removes & returnslst=[1,2,3]; lst.pop(1)2 (β†’ [1,3])
.clear()Removes alllst=[1,2,3]; lst.clear()[]
.index()Index of element[1,2,3,2].index(2)1
.count()Counts occurrences[1,2,2,3].count(2)2
.sort()Sorts in placelst=[3,1,2]; lst.sort()[1,2,3]
.reverse()Reverses in placelst=[1,2,3]; lst.reverse()[3,2,1]
.copy()Shallow copylst=[1,2]; lst2=lst.copy()[1,2]
List Comprehension & Tips
# List comprehension (fast, Pythonic)
squares = [x*x for x in range(5)]        # [0,1,4,9,16]
evens   = [x for x in range(10) if x%2==0]

# Sort with custom key
words = ["banana", "apple", "cherry"]
words.sort(key=len)

# Reverse sort
nums = [3, 1, 4, 1, 5]
nums.sort(reverse=True)                  # [5, 4, 3, 1, 1]

Most used: .append(), .extend(), .pop(), .sort(), .reverse(), .remove()

Tuple, Set & Dictionary
Tuple (immutable – only 2 methods)
MethodDescriptionExampleOutput
.index()Index of element(1,2,3,2).index(2)1
.count()Counts occurrences(1,2,2,3).count(2)2
Set Methods
MethodDescriptionExampleOutput
.add()Adds single elements={1,2}; s.add(3){1,2,3}
.update()Adds multiples={1,2}; s.update([3,4]){1,2,3,4}
.remove()Removes (error if missing)s={1,2,3}; s.remove(2){1,3}
.discard()Removes (no error)s={1,2,3}; s.discard(4){1,2,3}
.pop()Removes random elements={1,2,3}; s.pop()random
.clear()Removes alls.clear()set()
.union() / |Union{1,2}.union({2,3}){1,2,3}
.intersection() / &Intersection{1,2}.intersection({2,3}){2}
.difference() / -Difference{1,2}.difference({2,3}){1}
.symmetric_difference() / ^Symmetric diff{1,2}.symmetric_difference({2,3}){1,3}
.issubset()Subset check{1}.issubset({1,2})True
.issuperset()Superset check{1,2}.issuperset({1})True
.isdisjoint()No common elements{1}.isdisjoint({2})True
Dictionary Methods
MethodDescriptionExampleOutput
.keys()All keys{"a":1,"b":2}.keys()dict_keys(['a','b'])
.values()All values{"a":1,"b":2}.values()dict_values([1,2])
.items()Key-value pairs{"a":1,"b":2}.items()dict_items([('a',1),('b',2)])
.get()Value with default{"a":1}.get("b",0)0
.setdefault()Set default if missingd={}; d.setdefault("a",1)1
.update()Update with anotherd={"a":1}; d.update({"b":2}){'a':1,'b':2}
.pop()Remove key & return valued={"a":1,"b":2}; d.pop("a")1
.popitem()Remove last itemd={"a":1,"b":2}; d.popitem()('b',2)
.clear()Remove alld.clear(){}
.copy()Shallow copyd={"a":1}; d2=d.copy(){'a':1}
.fromkeys()Create from keysdict.fromkeys(['a','b'],0){'a':0,'b':0}
Set Operators & Dict Tips
# Set operators
a | b   # union
a & b   # intersection
a - b   # difference
a ^ b   # symmetric difference

# Set comparisons
s1.issubset(s2)      # s1 βŠ† s2
s1.issuperset(s2)    # s1 βŠ‡ s2
s1.isdisjoint(s2)    # no common elements

# Dict comprehension
squares = {x: x*x for x in range(5)}

# Merge dicts (Python 3.9+)
merged = d1 | d2
Numeric & Boolean
Method / OperationDescriptionExampleOutput
.bit_length()Bits to represent int(10).bit_length()4
.to_bytes()Convert to bytes(1024).to_bytes(2,"big")b'\x04\x00'
.from_bytes()Int from bytesint.from_bytes(b'\x04\x00',"big")1024
.as_integer_ratio()Ratio as tuple(3.5).as_integer_ratio()(7,2)
.is_integer()Float is integer?(5.0).is_integer()True
.hex()Hexadecimal string(255).hex()'0xff'
.realReal part(2+3j).real2.0
.imagImaginary part(2+3j).imag3.0
.conjugate()Complex conjugate(2+3j).conjugate()(2-3j)
Boolean: and, or, not, ==, !=, is, is not
Numeric Methods & Boolean Short-Circuit
# Integer & Float attributes
(10).numerator        # 10
(10).denominator      # 1

# Short-circuit behavior
x = 0 or "default"    # "default"
y = 5 and 10          # 10
Control Flow, Slicing & Operators
Conditional & Loops
if x > 5: print("Big")
if age >= 18: print("Adult") else: print("Minor")
if marks>=90: grade="A" elif marks>=75: grade="B" else: grade="C"
# ternary: "Pass" if score>=40 else "Fail"

while i <= 3: print(i); i += 1
for fruit in ["apple","banana"]: print(fruit)
for i in range(1,4): print(i)
for k,v in d.items(): print(k,v)

# break, continue, pass, loop else
# match-case (Python 3.10+)
match x:
    case 1: print("One")
    case 2: print("Two")
    case _: print("Other")
Slicing
SliceSyntaxExampleOutput
Basic[start:stop]"Python"[1:4]"yth"
Start only[start:]"Python"[2:]"thon"
Stop only[:stop]"Python"[:3]"Pyt"
Full copy[:]"Python"[:]"Python"
With step[::step]"Python"[::2]"Pto"
Reverse[::-1]"Python"[::-1]"nohtyP"
Negative[-3:]"Python"[-3:]"hon"
Operators
CategoryOperators
Arithmetic+ - * / // % **
Bitwise& | ^ ~ << >>
Comparison== != < > <= >=
Logicaland or not
Assignment= += -= *= /= //= %= **=
Membershipin, not in
Identityis, is not
Range() Variations & Iteration Patterns
Range FormatExampleSequence
range(stop)range(5)0,1,2,3,4
range(start, stop)range(2,6)2,3,4,5
range(start, stop, step)range(1,10,2)1,3,5,7,9
range(start, stop, -step)range(5,0,-1)5,4,3,2,1
# Special patterns
for i, val in enumerate(["a","b"]): print(i, val)
for n, a in zip(names, ages): print(n, a)
for i in reversed([1,2,3]): print(i)
for i in sorted([3,1,2]): print(i)

Precedence: ** β†’ ~+- β†’ */%// β†’ +- β†’ <<>> β†’ & β†’ ^ β†’ | β†’ comparisons β†’ ==!= β†’ assignments β†’ is/is not β†’ in/not in β†’ not β†’ and β†’ or

Functions
def greet(name="World"): return f"Hello {name}"
def add(a, b): return a + b
def sum_all(*args): return sum(args)
def print_info(**kwargs): ...
square = lambda x: x * x

# decorators, generators, closures
def decorator(func):
    def wrapper(): print("Before"); func(); print("After")
    return wrapper

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

Key: *args, **kwargs, global, nonlocal, lambda, yield, @decorator, type hints.

Function Types & Advanced Concepts
TypeExample
Lambdasquare = lambda x: x*x
Filterlist(filter(lambda x: x%2==0, nums))
Maplist(map(lambda x: x**2, [1,2,3]))
Recursivedef factorial(n): return 1 if n<=1 else n*factorial(n-1)
Closuredef multiplier(n): return lambda x: x*n
Decorator w/ args@repeat(3) β†’ runs function 3 times
# Special parameters
def func(a, b, /): ...        # positional only
def func(*, a, b): ...        # keyword only
def func(a, /, b, *, c): ...  # combined

# Function attributes
hello.__name__        # 'hello'
hello.__doc__         # docstring
add.__annotations__   # {'a': int, 'b': int, 'return': int}
Exception Handling
try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except (ValueError, TypeError) as e:
    print(f"Error: {e}")
else:
    print("Success")
finally:
    print("Cleanup")

raise ValueError("Invalid")
class MyError(Exception): pass
assert radius > 0, "Radius must be positive"

Built-in exceptions: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError, etc.

Complete Exception Handling Reference
TypeExample
Basictry: ... except: ...
Specificexcept ValueError as e:
Multipleexcept (TypeError, ValueError):
Full blocktry/except/else/finally
Raiseraise ValueError("msg")
Re-raiseexcept: raise
Customclass MyError(Exception): pass
Chainingraise ValueError(...) from e
Suppresswith suppress(FileNotFoundError):
Assertassert x > 0, "must be positive"

Hierarchy: BaseException β†’ Exception β†’ ArithmeticError, LookupError, etc.

OOPS Concepts
class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return f"Hi {self.name}"

class Animal:
    def speak(self): pass
class Dog(Animal):
    def speak(self): return "Woof"

@property
def radius(self): return self.__radius

Pillars: Encapsulation, Inheritance, Polymorphism, Abstraction. __str__, __repr__, @classmethod, @staticmethod, super().

OOPS Complete Reference
PillarDescription
EncapsulationBundle data + methods; private via __attr
Inheritanceclass Child(Parent) β€” reuse code
PolymorphismSame method, different behavior
AbstractionHide complexity via ABC / interfaces
# Inheritance types
class A: pass
class B(A): pass                        # Single
class C(A): pass
class D(B, C): pass                     # Multiple
class E(D): pass                        # Multilevel
# Hierarchical: multiple children from one parent
# Hybrid: combination of above

# Special methods
__init__, __str__, __repr__, __len__,
__getitem__, __call__, __eq__, __slots__

# Class & static methods
@classmethod def create(cls): return cls()
@staticmethod def add(a, b): return a + b

# Property decorator
@property def radius(self): return self.__radius
@radius.setter def radius(self, value): self.__radius = value

Polymorphism types: Compile-time (overloading), Runtime (overriding), Duck typing, Operator overloading.

File Handling & Advanced
with open("data.txt", "r") as f:
    content = f.read()

with open("out.txt", "w") as f:
    f.write("Hello")

import json, csv, pickle, os

async def main(): await asyncio.sleep(1)
threading.Thread(target=func).start()

Modes: r, w, a, r+, w+, a+, rb, wb. Context managers, JSON, CSV, pickle, threading, async.

File Handling & Advanced Topics
ModeDescriptionPointer
rRead onlyStart
wWrite (overwrite)Start
aAppendEnd
r+Read & writeStart
w+Write & readStart
a+Append & readEnd
rb / wbBinary read / writeβ€”
# Reading methods
f.read(), f.read(n), f.readline(), f.readlines()
for line in f:  # memory efficient

# File methods
f.seek(pos), f.tell(), f.close(), f.flush()

# OS operations
os.path.exists(), os.remove(), os.rename()
os.listdir(), os.mkdir(), os.getcwd()

# CSV / JSON / Pickle
csv.reader(f), csv.writer(f)
json.load(f), json.dump(data, f)
pickle.dump(data, f), pickle.load(f)

Advanced: iterators, generators, threading, multiprocessing, async/await, memory management, metaclasses, descriptors, context managers, decorators.

Variables
TypeExample
Basicx = 10
Multiplea, b = 5, 10
Chainx = y = z = 0
Swapa, b = b, a
Valid namesmy_var, _private, var2, MAX_SIZE
Invalid names2var, my-var, class
Scopelocal, global, enclosing, built-in
Modifiersglobal, nonlocal
Unpackinga, b, c = [1, 2, 3]
Extended unpackingfirst, *rest = [1,2,3,4]
ConstantsPI = 3.14, MAX_USERS = 100
Special__name__, __file__, __doc__
Walrusif (n := len(data)) > 10:
Type Hintsage: int = 25
Deletedel x
# Type checking
type(10)                # <class 'int'>
isinstance(10, int)     # True

# Memory & identity
x = 10
id(x)                   # memory address
a = [1,2]; b = [1,2]
a == b                  # True (value)
a is b                  # False (identity)

# Special assignments
x = 10 if flag else 0   # ternary
with open("file.txt") as f: data = f.read()
Variable Tricks & Common Errors
# Swap without temp
a, b = b, a

# Multiple return
x, y = get_coords()

# Default dict value
value = dict.get(key, default)

# Safe key check
if 'key' in dict: ...

# Short-circuit default
name = user_input or "Guest"

Common errors: NameError (undefined), UnboundLocalError, AttributeError, TypeError.

Naming: snake_case (vars), UPPER_CASE (constants), CamelCase (classes), _private, __dunder__.

About

Latest SeaDesk.in started out as a small project and is now the fastest growing SeaDesk.in Updates of all times in India.