Complete Reference · Free Download

Python
Cheat Sheet

Every essential Python concept in one place — syntax, data types, OOP, comprehensions, file I/O, exceptions, modules, and more. Curated for beginners to advanced developers.

Browse Cheat Sheet ↓
12+Topics Covered
300+Code Snippets
8 pagesPDF Download
FreeAlways
Basics

Python Syntax & Basics

The building blocks — variables, print, comments, input, and type casting.

🔤
Variables & Print
Dynamic typing — no need to declare types. print() outputs to console.
python
# Variable assignment — no type declaration
name = "Alice"
age  = 25
pi   = 3.14159
is_dev = True

# Multiple assignment
x, y, z = 1, 2, 3
a = b = c = 0

# Print with f-string (Python 3.6+)
print(f"Hello, {name}! Age: {age}")
print(f"{name!r}")        # repr
print(f"{pi:.2f}")        # formatted float
print("sep", "test", sep="-", end="!\n")
🔄
Type Casting & Input
Convert between types using built-in casting functions.
python
# Type casting
int("42")        # → 42
float("3.14")    # → 3.14
str(100)          # → "100"
bool(0)           # → False
list((1,2,3))     # tuple → list
tuple([1,2,3])   # list → tuple

# Input (always returns string)
name = input("Enter name: ")
age  = int(input("Enter age: "))

# Check type
type(name)         # <class 'str'>
isinstance(age, int)  # True
Data Types

Built-in Data Types

Lists, tuples, sets, dicts, and strings — with the most-used methods.

📝
Strings
Immutable sequences. Rich set of built-in methods.
python
s = "Hello, Python!"

# Slicing  [start:stop:step]
s[0:5]        # "Hello"
s[::-1]       # reversed

# Methods
s.upper()       # "HELLO, PYTHON!"
s.lower()       # "hello, python!"
s.strip()       # remove whitespace
s.split(",")    # ["Hello", " Python!"]
s.replace("Python","World")
s.find("Python")  # 7
s.startswith("Hello")  # True
s.count("l")    # 3
",".join(["a","b","c"])  # "a,b,c"
len(s)          # 14
📋
Lists
Ordered, mutable sequences. Zero-indexed.
python
nums = [3, 1, 4, 1, 5, 9]

nums.append(2)       # add to end
nums.insert(2, 99)    # insert at index
nums.remove(1)       # removes first 1
nums.pop()           # removes & returns last
nums.pop(0)          # removes & returns first
nums.sort()          # in-place sort
nums.sort(reverse=True)
nums.reverse()       # in-place reverse
sorted(nums)         # returns new sorted list
nums.index(5)        # → 4
nums.count(1)        # → 2
nums.extend([6,7])   # merge list
nums.copy()          # shallow copy
🗂️
Dictionaries
Key-value pairs. Keys must be hashable. Ordered since Python 3.7.
python
d = {"name": "Alice", "age": 25}

d["email"] = "alice@email.com"  # add/update
d.get("phone", "N/A")  # safe get
d.update({"city": "Delhi"})
del d["age"]             # delete key
d.pop("name")            # remove & return

d.keys()    # dict_keys([...])
d.values()  # dict_values([...])
d.items()   # dict_items([(k,v)])

# Iterate
for k, v in d.items():
    print(k, v)

"name" in d    # True
d.setdefault("score", 0)
🎯
Sets & Tuples
Sets are unordered unique collections. Tuples are immutable lists.
python
# Sets — unordered, unique
s = {1, 2, 3, 3}     # → {1, 2, 3}
s.add(4)
s.discard(2)
s.remove(1)         # raises if missing
a | b               # union
a & b               # intersection
a - b               # difference
a ^ b               # symmetric diff
a.issubset(b)

# Tuples — immutable
t = (1, 2, 3)
t[0]               # → 1 (access)
x, y, z = t        # unpack
t.count(1)         # → 1
t.index(2)         # → 1
(1,) + (2,3)        # concat
Operators

Operators Quick Reference

Arithmetic & Assignment
Op Example Result
+ 5 + 3 8
- 5 - 3 2
* 5 * 3 15
/ 7 / 2 3.5
// 7 // 2 3
% 7 % 2 1
** 2 ** 8 256
+= x += 5 x = x+5
-= x -= 2 x = x-2
⚖️
Comparison & Logical
Op Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
and Logical AND
or Logical OR
not Logical NOT
🔍
Identity, Membership & Bitwise
Op Meaning
is Same object
is not Not same object
in Membership test
not in Not in sequence
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< >> Bit shift
Control Flow

Conditionals & Loops

🔀
if / elif / else
python
score = 82

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"

# Ternary / inline
status = "pass" if score >= 60 else "fail"

# Walrus operator (3.8+)
if n := len([1,2,3]):
    print(f"List has {n} items")

# match-case (3.10+)
match grade:
    case "A": print("Excellent!")
    case "B": print("Good")
    case _:   print("Keep going")
🔁
for / while Loops
python
# for loop
for i in range(5):          # 0..4
    print(i)

for i in range(2, 10, 2): # 2,4,6,8
    print(i)

for idx, val in enumerate(["a","b"]):
    print(idx, val)

for a, b in zip([1,2],[3,4]):
    print(a, b)

# while loop
n = 0
while n < 5:
    n += 1
else:                   # runs if no break
    print("done")

# Control statements
break      # exit loop
continue   # skip iteration
pass       # no-op placeholder
Functions

Functions & Lambdas

⚙️
Defining Functions
python
def greet(name: str, greeting: str = "Hello") -> str:
    """Return a greeting string."""
    return f"{greeting}, {name}!"

# *args — variable positional
def total(*nums):
    return sum(nums)

# **kwargs — variable keyword
def info(**kwargs):
    for k, v in kwargs.items():
        print(f"{k}: {v}")

# Unpacking args
nums = [1, 2, 3]
total(*nums)               # → 6

# Return multiple values (tuple)
def divmod_custom(a, b):
    return a // b, a % b

q, r = divmod_custom(10, 3)
λ
Lambda, map, filter, reduce
python
# Lambda — anonymous single-expression fn
square = lambda x: x ** 2
add    = lambda a, b: a + b

# map — apply fn to all items
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))

# filter — keep items where fn is True
evens = list(filter(lambda x: x%2==0, nums))

# reduce — accumulate to single value
from functools import reduce
product = reduce(lambda a,b: a*b, nums)  # 24

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

# Closures
def make_multiplier(n):
    return lambda x: x * n
double = make_multiplier(2)
OOP

Object-Oriented Programming

🧬
Classes, Inheritance & Dunder Methods
python
class Animal:
    species = "Unknown"           # class var

    def __init__(self, name, age):
        self.name = name         # instance var
        self._age  = age         # protected

    def speak(self):
        return f"{self.name} makes a sound"

    def __str__(self):   # str(obj)
        return f"Animal({self.name})"
    def __repr__(self):  # repr(obj)
        return f"Animal({self.name!r})"
    def __len__(self):   # len(obj)
        return self._age

class Dog(Animal):         # inheritance
    species = "Canis"

    def speak(self):         # override
        return "Woof!"

    def fetch(self, item):   # new method
        return f"{self.name} fetched {item}"

d = Dog("Buddy", 3)
isinstance(d, Animal)   # True
super().__init__(...)    # call parent
🏗️
Properties, Decorators & dataclass
python
class Circle:
    def __init__(self, radius):
        self._r = radius

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

    @radius.setter
    def radius(self, v):
        if v < 0: raise ValueError
        self._r = v

    @staticmethod
    def info(): return "A circle"

    @classmethod
    def unit(cls): return cls(1)

# dataclass (Python 3.7+)
from dataclasses import dataclass, field

@dataclass
class Point:
    x: float
    y: float
    label: str = "origin"
    tags: list = field(default_factory=list)

p = Point(1.0, 2.0)  # auto __init__, __repr__
Comprehensions

Comprehensions & Generators

🔁
List, Dict & Set Comprehensions
python
# List comprehension
squares  = [x**2 for x in range(10)]
evens    = [x for x in range(20) if x%2==0]
flat     = [n for row in matrix for n in row]

# Dict comprehension
sq_map   = {x: x**2 for x in range(5)}
inverted = {v: k for k,v in sq_map.items()}

# Set comprehension
unique_sq = {x**2 for x in [-2,-1,0,1,2]}

# Nested comprehension
matrix = [[1 if r==c else 0
           for c in range(3)]
          for r in range(3)]   # identity matrix
Generators & yield
python
# Generator expression (lazy)
gen = (x**2 for x in range(1_000_000))
next(gen)          # → 0  (no memory overhead)

# Generator function
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
[next(fib) for _ in range(8)]
# [0,1,1,2,3,5,8,13]

# yield from
def chain(*iterables):
    for it in iterables:
        yield from it

# itertools essentials
from itertools import islice, chain, product
list(islice(fibonacci(), 10))
Exceptions

Exception Handling

🚨
try / except / finally
python
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Math error: {e}")
except (TypeError, ValueError) as e:
    print(f"Type/Value error: {e}")
except Exception as e:
    print(f"Unexpected: {e}")
    raise               # re-raise
else:
    print("No exception!") # runs if no except
finally:
    print("Always runs")  # cleanup

# Custom exception
class ValidationError(Exception):
    def __init__(self, field, msg):
        super().__init__(msg)
        self.field = field

raise ValidationError("email", "Invalid")
📋
Common Exception Types
Exception When raised
ValueError Wrong value type
TypeError Wrong argument type
IndexError Index out of range
KeyError Dict key missing
AttributeError Attribute missing
NameError Variable not defined
FileNotFoundError File missing
ImportError Module not found
StopIteration Iterator exhausted
RuntimeError Generic runtime
OverflowError Arithmetic overflow
RecursionError Max recursion depth
File I/O

File & Path Operations

📄
Reading & Writing Files
python
# Context manager (auto-close)
with open("data.txt", "r") as f:
    content = f.read()      # entire file
    lines   = f.readlines() # list of lines
    line    = f.readline()  # one line

# Write (overwrites)
with open("out.txt", "w") as f:
    f.write("Hello!\n")
    f.writelines(["line1\n", "line2\n"])

# Append
with open("log.txt", "a") as f:
    f.write("new entry\n")

# Binary mode
with open("img.png", "rb") as f:
    data = f.read()

# Modes: r w a x rb wb ab r+ w+
📂
pathlib & JSON/CSV
python
from pathlib import Path
p = Path("data") / "file.txt"
p.exists(); p.is_file(); p.is_dir()
p.read_text(); p.write_text("hi")
p.mkdir(parents=True, exist_ok=True)
list(p.parent.glob("*.txt"))
p.suffix; p.stem; p.name

# JSON
import json
data = {"name": "Alice", "age": 25}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)

# CSV
import csv

with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    rows = [row for row in reader]
Modules

Modules, Packages & Standard Library

📦
Imports
python
import math
import os as operating_sys

from datetime import datetime, date
from collections import Counter, defaultdict
from typing import List, Dict, Optional

from . import sibling_module       # relative
from ..pkg import something         # up a level

# Conditional import
try:
    import ujson as json
except ImportError:
    import json

# __name__ guard
if __name__ == "__main__":
    main()
🕐
datetime & os
python
from datetime import datetime

now = datetime.now()

now.strftime("%Y-%m-%d %H:%M:%S")

datetime.strptime(
    "2024-01-15",
    "%Y-%m-%d"
)

datetime.today().year


import os

os.getcwd()
os.listdir(".")
os.path.join("data", "file.txt")
os.path.exists("path")
os.environ.get("HOME")
os.makedirs("a/b/c", exist_ok=True)


import sys

sys.argv # command-line args
sys.exit(0) # exit program
sys.path # module search path
🧰
collections & functools
python
from collections import Counter, deque, defaultdict, OrderedDict

Counter("abracadabra")   # {'a':5,...}
Counter.most_common(3)

dq = deque(
    [1, 2, 3],
    maxlen=5
)

dq.appendleft(0)
dq.rotate(2)

dd = defaultdict(list)
dd["key"].append(1)   # no KeyError


from functools import lru_cache, partial, wraps

@lru_cache(maxsize=None)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)

double = partial(pow, exp=2)
Built-ins

Essential Built-in Functions

  • len()Length of sequence
  • range()Int sequence
  • enumerate()Index + value
  • zip()Pair iterables
  • map()Apply function
  • filter()Filter items
  • sorted()New sorted list
  • reversed()Reverse iterator
  • sum()Total of iterable
  • min()Minimum value
  • max()Maximum value
  • abs()Absolute value
  • type()Get object type
  • isinstance()Type check
  • hasattr()Has attribute?
  • getattr()Get attribute
  • setattr()Set attribute
  • dir()List attributes
  • open()Open file
  • print()Output to stdout
  • input()Read from stdin
  • repr()Repr string
  • hash()Hash of object
  • id()Memory address
🐍

Download the Full PDF Cheat Sheet

Get all 12 topics in a beautifully formatted 8-page PDF — perfect to pin on your desk or keep on your phone.

↑ Back to Top

No spam. Download link sent to your email instantly.

🎓 Featured Courses

Level Up Your Python Skills

Go beyond the cheat sheet. Join our industry-expert-led courses and build real projects.

⭐ 4.8
Python
Python Masterclass — Zero to Expert
Master Python from zero to advanced with real-world projects and AI integration.
⏱️ 2 months 📚 50+ lessons 🏆 Certificate
₹5,999 ₹15,999 60% OFF
⭐ 4.8
Data Science + AI
Python for Data Science
Python is the most popular programming language for data science due to its simplicity, versatility, and a vast ecosystem of open-source libraries
⏱️ 4 months 📚 150+ lessons 🏆 Certificate
₹9,999 ₹16,999 38% OFF
⭐ 4.8
Data Analysis
Data Analysis with Excel & Python
Python in Excel – making it possible to integrate Python and Excel analytics within the same Excel grid for uninterrupted workflow.
⏱️ 3 months 📚 120+ lessons 🏆 Certificate
₹12,999 ₹18,000 28% OFF
📬

Get New Cheat Sheets First

We release new cheat sheets every week. Subscribe and get them free in your inbox before anyone else.

No spam. Unsubscribe anytime.

Join WhatsApp Channel