Skip to content

Python Cheatsheet — Complete Quick Reference

DodaTech 2 min read

In this tutorial, you'll learn about Python Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Python syntax, built-in data structures, control flow, functions, classes, file I/O, and common patterns — condensed into one dense reference for everyday use.

Variables & Data Types

x = 10            # int (dynamic typing)
y = 3.14          # float
name = "Python"   # str
is_ok = True      # bool
Type Example Mutable
int 42
float 3.14
str "hi" No
list [1, 2] Yes
tuple (1, 2) No
dict {"a": 1} Yes
set {1, 2} Yes

Strings

s = f"Hello {name}"     # f-string (3.6+)
s.upper(); s.lower(); s.strip()
s.split(","); ",".join(["a","b"])
s.startswith("H"); s.find("P")

Lists

nums = [1, 2, 3]
nums.append(4); nums.pop(); nums.sort()
nums[0]; nums[-1]; nums[1:3]  # slice
[x*2 for x in nums]           # list comprehension

Dicts

d = {"a": 1, "b": 2}
d.get("c", 0); d.keys(); d.values(); d.items()
for k, v in d.items(): ...

Tuples & Sets

t = (1, 2)          # immutable
s = {1, 2, 2, 3}    # {1, 2, 3} — duplicates removed
s.add(4); s.remove(1); s & {2, 3}; s | {4, 5}

Control Flow

if x > 0: ...
elif x == 0: ...
else: ...

for i in range(5): ...
while x > 0: ...

# match-case (3.10+)
match status:
    case 200: ...
    case _: ...

Functions & Lambda

def add(a, b=0): return a + b
f = lambda x: x * 2
# *args, **kwargs
def log(*args, **kwargs): ...

Classes

class Dog:
    species = "Canine"                 # class var
    def __init__(self, name):          # constructor
        self.name = name               # instance var
    def bark(self): return f"{self.name} says woof"

File I/O

with open("file.txt", "r") as f:
    content = f.read()          # str
    lines = f.readlines()       # list[str]
# Modes: r, w, a, r+, rb, wb

Exceptions

try:
    x = 1 / 0
except ZeroDivisionError:
    print("can't divide by zero")
except Exception as e:
    print(e)
finally:
    cleanup()

Imports

import math; math.sqrt(16)
from os import path; path.join("a","b")
from collections import defaultdict, Counter

Comprehensions

[x*2 for x in range(10) if x % 2 == 0]      # list
{k: v*2 for k, v in d.items()}               # dict
{x for x in nums if x > 0}                   # set
What is the difference between a list and a tuple in Python?

A list is mutable (can be changed after creation) and uses square brackets []. A tuple is immutable (cannot be changed) and uses parentheses (). Tuples are faster and can be used as dictionary keys.

What does the `with` statement do in Python?

The with statement is used for resource management. It automatically calls __enter__ and __exit__ methods on an object, ensuring resources like file handles or network connections are properly cleaned up even if an error occurs.

What is a list comprehension?

A list comprehension is a concise way to create lists by applying an expression to each item in an iterable, optionally filtering with a condition. Example: [x**2 for x in range(10) if x % 2 == 0] produces [0, 4, 16, 36, 64]

See the full Python tutorial series for deeper dives.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro