500+ Tools 100% Free Forever No Subscriptions No Sign Up Required
  1. Home
  2. De
  3. Python Cheat Sheet
Python Cheatsheet – Syntax, Snippets & Examples | FreeToolr
Python Cheatsheet

The Ultimate Python Reference

Quick syntax snippets, code examples, and essential patterns – all in one place. Copy, paste, and level up.

50+
Snippets
10
Categories
Free
Forever
Copy
One Click
Showing all Python snippets

Python Basics (5 snippets)

Core syntax: variables, data types, basic operators, and input/output.

</> Variables & Assignment

Declare variables with dynamic typing – no type declaration needed.

# Variable assignment
name = "Alice"
age = 30
height = 5.8
is_student = True

# Multiple assignment
a, b, c = 1, 2, 3

# Type checking
print(type(name))   # <class 'str'>
print(type(age))    # <class 'int'>
variables assignment types
</> Basic Data Types

Python's core built-in data types – int, float, str, bool, None.

# Numeric types
integer = 42
floating = 3.14159
complex_num = 2 + 3j

# Text type
text = "Hello, World!"

# Boolean & None
flag = False
nothing = None

# Type conversion
num_str = str(100)      # "100"
num_int = int("200")    # 200
int float str bool None types
</> Arithmetic Operators

Standard math operators plus floor division and exponentiation.

# Basic arithmetic
sum_val = 10 + 5       # 15
diff = 10 - 5          # 5
prod = 10 * 5          # 50
quot = 10 / 3          # 3.333...

# Special operators
floor_div = 10 // 3    # 3 (integer division)
modulo = 10 % 3        # 1 (remainder)
power = 2 ** 8         # 256 (exponentiation)
operators math arithmetic
</> Comparison & Logical

Boolean expressions with comparison and logical operators.

# Comparison operators
x, y = 10, 20
print(x == y)   # False
print(x != y)   # True
print(x < y)    # True
print(x >= 10)  # True

# Logical operators
print(x > 5 and y < 30)   # True
print(x > 15 or y < 30)   # True
print(not x > 15)          # True

# Chained comparison
print(5 < x < 15)  # True
comparison logical boolean and or not
</> Input & Output

Reading user input and printing formatted output.

# Reading input (always returns string)
user_name = input("Enter your name: ")

# Basic printing
print("Hello,", user_name)

# f-strings (Python 3.6+)
age = 25
print(f"{user_name} is {age} years old.")

# Format specifiers
pi = 3.14159265
print(f"Pi ≈ {pi:.2f}")  # Pi ≈ 3.14

# sep & end parameters
print("A", "B", "C", sep="-")  # A-B-C
print("Line 1", end=" | ")
print("Line 2")  # Line 1 | Line 2
input print f-string output

Control Flow (5 snippets)

Conditional statements, loops, and control flow keywords.

</> if / elif / else

Conditional branching based on boolean expressions.

score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'F'

print(f"Grade: {grade}")  # Grade: B

# Ternary (conditional expression)
status = "Pass" if score >= 60 else "Fail"
if elif else ternary conditional
</> for Loop

Iterate over sequences – lists, strings, ranges, and more.

# Looping over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Using range()
for i in range(5):          # 0 to 4
    print(i, end=" ")       # 0 1 2 3 4

for i in range(2, 8, 2):    # start=2, stop=8, step=2
    print(i, end=" ")       # 2 4 6

# Looping over dict keys/values
person = {"name": "Alice", "age": 30}
for key, value in person.items():
    print(f"{key}: {value}")
for loop range iteration
</> while Loop

Repeat a block while a condition remains true.

# Basic while loop
count = 0
while count < 5:
    print(count, end=" ")
    count += 1
# Output: 0 1 2 3 4

# while with break & continue
num = 0
while True:
    num += 1
    if num == 3:
        continue   # skip 3
    if num > 6:
        break      # exit loop
    print(num, end=" ")
# Output: 1 2 4 5 6
while loop break continue
</> break, continue, pass

Control loop execution with break, continue, and pass.

# break - exit loop entirely
for i in range(10):
    if i == 5:
        break
    print(i, end=" ")  # 0 1 2 3 4

# continue - skip current iteration
for i in range(6):
    if i % 2 == 0:
        continue
    print(i, end=" ")  # 1 3 5

# pass - do nothing (placeholder)
def future_function():
    pass  # TODO: implement later
break continue pass control
</> match / case (3.10+)

Structural pattern matching – Python's switch-case equivalent.

# Python 3.10+ pattern matching
def handle_command(cmd):
    match cmd:
        case "start":
            return "Starting..."
        case "stop":
            return "Stopping..."
        case "pause" | "resume":
            return "Toggling state..."
        case _:
            return "Unknown command"

print(handle_command("pause"))  # Toggling state...
match case pattern 3.10

Functions & Lambdas (4 snippets)

Defining functions, arguments, return values, lambda expressions, and decorators.

</> Function Definition

Define reusable blocks with def, parameters, and return values.

# Basic function

def greet(name):
    """Return a greeting message."""
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

# Multiple return values (tuple unpacking)
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 1, 7, 2, 9])
print(low, high)  # 1 9
def function return docstring
</> Arguments & Parameters

Positional, keyword, default, *args, and **kwargs explained.

# Default parameters
def power(base, exp=2):
    return base ** exp

print(power(5))      # 25 (exp defaults to 2)
print(power(2, 10)) # 1024

# *args (variable positional)
def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3, 4))  # 10

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

print_info(name="Bob", age=25)
*args **kwargs default parameters
</> Lambda Functions

Anonymous single-expression functions for concise callbacks.

# Basic lambda
square = lambda x: x ** 2
print(square(7))  # 49

# Lambda with multiple args
add = lambda a, b: a + b
print(add(3, 5))  # 8

# Used with built-in functions
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

# Sorting with lambda
pairs = [(1, 3), (4, 1), (2, 2)]
pairs.sort(key=lambda p: p[1])
print(pairs)  # [(4, 1), (2, 2), (1, 3)]
lambda anonymous filter sort
</> Decorators

Wrap functions to extend behaviour without modifying them.

# Simple decorator

def timer(func):
    import time
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time()-start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    import time
    time.sleep(0.5)
    return "Done"

print(slow_function())
decorator @ wrapper higher-order

Data Structures (4 snippets)

Lists, tuples, dictionaries, sets, and common operations on each.

</> Lists

Ordered, mutable sequences – Python's workhorse data structure.

# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]

# Indexing & slicing
print(fruits[0])      # apple
print(fruits[-1])     # cherry
print(fruits[1:3])    # ['banana', 'cherry']

# Common methods
fruits.append("date")
fruits.insert(1, "blueberry")
fruits.remove("banana")
popped = fruits.pop()  # removes last
fruits.sort(reverse=True)
list append slice sort mutable
</> Tuples

Ordered, immutable sequences – perfect for fixed collections.

# Creating tuples
point = (3, 4)
colors = "red", "green", "blue"  # packing

# Unpacking
x, y = point
print(x, y)  # 3 4

# Single-element tuple (note comma!)
single = (42,)

# Named tuples
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
alice = Person(name="Alice", age=30)
print(alice.name, alice.age)
tuple immutable unpacking namedtuple
</> Dictionaries

Key-value pairs – fast lookups, flexible keys (hashable types).

# Creating dicts
person = {"name": "Alice", "age": 30}
scores = dict(math=95, english=88)

# Access & modify
print(person["name"])         # Alice
print(person.get("city", "N/A"))  # N/A (safe access)
person["city"] = "New York"

# Looping
for key, value in person.items():
    print(f"{key}: {value}")

# Dict comprehension
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
dict dictionary key-value get
</> Sets

Unordered collections of unique elements with set operations.

# Creating sets
a = {1, 2, 3, 4}
b = set([3, 4, 5, 6])

# Set operations
print(a | b)  # Union: {1, 2, 3, 4, 5, 6}
print(a & b)  # Intersection: {3, 4}
print(a - b)  # Difference: {1, 2}
print(a ^ b)  # Symmetric diff: {1, 2, 5, 6}

# Useful methods
a.add(5)
a.remove(2)
print(3 in a)  # True (fast membership test)
set unique union intersection

String Operations (4 snippets)

String formatting, slicing, common methods, and f-string tricks.

</> String Methods

Common string manipulation methods for everyday use.

text = "  Hello, Python World!  "

# Stripping whitespace
print(text.strip())       # "Hello, Python World!"
print(text.lstrip())      # left strip
print(text.rstrip())      # right strip

# Case conversion
print(text.upper())       # "  HELLO, PYTHON WORLD!  "
print(text.lower())
print(text.title())       # "  Hello, Python World!  "

# Find & replace
print(text.replace("Python", "Java"))
print(text.find("World"))  # 15 (index)
string strip upper replace find
</> f-String Formatting

Modern string interpolation with expressions and format specs.

name = "Alice"
age = 30
pi = 3.14159265

# Basic interpolation
print(f"{name} is {age} years old.")

# Expressions inside f-strings
print(f"Next year: {age + 1}")

# Format specifiers
print(f"Pi: {pi:.3f}")        # 3.142
print(f"Percent: {0.875:.1%}") # 87.5%
print(f"Hex: {255:#x}")       # 0xff
print(f"Padded: {42:05d}")    # 00042

# Alignment
print(f"{'Left':<10}|{'Right':>10}")
f-string format interpolation specifier
</> String Slicing

Extract substrings using [start:stop:step] notation.

text = "Hello, World!"

# Basic slicing
print(text[0:5])     # "Hello"
print(text[7:])      # "World!"
print(text[:5])      # "Hello"
print(text[-6:-1])   # "World"

# With step
print(text[::2])     # "Hlo ol!" (every 2nd char)
print(text[::-1])    # "!dlroW ,olleH" (reverse)

# Slice assignment (lists)
chars = list(text)
chars[7:12] = list("Earth")
print(''.join(chars))  # "Hello, Earth!"
slice substring reverse step
</> join & split

Convert between strings and lists with join() and split().

# split() - string to list
csv = "apple,banana,cherry"
fruits = csv.split(",")
print(fruits)  # ['apple', 'banana', 'cherry']

# split with maxsplit
line = "a b c d e"
print(line.split(" ", 2))  # ['a', 'b', 'c d e']

# join() - list to string
words = ["Hello", "World"]
sentence = " ".join(words)
print(sentence)  # "Hello World"

# join with different separator
path = "/".join(["usr", "local", "bin"])
print(path)  # "usr/local/bin"
join split list delimiter

Comprehensions (2 snippets)

Concise ways to create lists, dicts, and sets with conditional filtering.

</> List Comprehension

Create lists in a single line – faster and more Pythonic than loops.

# Basic
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# With conditional filter
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# With if/else (ternary)
labels = ["even" if x % 2 == 0 else "odd" for x in range(6)]
# ['even', 'odd', 'even', 'odd', 'even', 'odd']

# Nested loops
pairs = [(x, y) for x in range(3) for y in range(2)]
# [(0,0), (0,1), (1,0), (1,1), (2,0), (2,1)]
list comprehension pythonic filter nested
</> Dict & Set Comprehension

Build dictionaries and sets using the same compact syntax.

# Dict comprehension
square_map = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Filtering dict
ages = {"Alice": 30, "Bob": 25, "Charlie": 35}
adults = {k: v for k, v in ages.items() if v >= 30}
# {'Alice': 30, 'Charlie': 35}

# Set comprehension
unique_lengths = {len(word) for word in ["hi", "hello", "hey", "world"]}
# {2, 3, 5}

# Generator expression (memory-efficient)
sum_of_squares = sum(x**2 for x in range(1000000))
dict comprehension set comprehension generator

File I/O (3 snippets)

Reading from and writing to files, context managers, and path handling.

</> Reading Files

Open and read files safely using context managers (with statement).

# Read entire file
with open("data.txt", "r") as f:
    content = f.read()

# Read line by line
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()

# Read with encoding
with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()
open read with context manager file
</> Writing Files

Write data to files – overwrite, append, and create new files.

# Write (overwrites)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line.\n")

# Append (adds to end)
with open("log.txt", "a") as f:
    f.write(f"New log entry at {time.ctime()}\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

# Create file if not exists (x mode)
try:
    with open("new_file.txt", "x") as f:
        f.write("Fresh file!")
except FileExistsError:
    print("File already exists")
write append writelines file
</> Working with Paths

Use pathlib for modern, cross-platform file path handling.

from pathlib import Path

# Create Path object
p = Path("/usr/local/bin/script.py")

# Path properties
print(p.name)       # script.py
print(p.stem)       # script
print(p.suffix)     # .py
print(p.parent)     # /usr/local/bin

# Check existence
if p.exists():
    print("File exists!")

# Iterate over directory
for file in Path(".").glob("*.py"):
    print(file.name)

# Create directory
Path("new_folder").mkdir(exist_ok=True)
pathlib Path glob directory

OOP in Python (4 snippets)

Classes, inheritance, dunder methods, properties, and object-oriented patterns.

</> Class Definition

Define classes with __init__, attributes, and instance methods.

class Dog:
    """A simple Dog class."""
    species = "Canis familiaris"  # class attribute

    def __init__(self, name, age):
        self.name = name  # instance attribute
        self.age = age

    def bark(self):
        return f"{self.name} says Woof!"

    def __str__(self):
        return f"{self.name} ({self.age} years)"

# Creating instances
buddy = Dog("Buddy", 3)
print(buddy.bark())   # Buddy says Woof!
print(str(buddy))     # Buddy (3 years)
class __init__ self instance OOP
</> Inheritance

Extend classes with inheritance and super() for parent access.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name)
        self.color = color

    def speak(self):
        return f"{self.name} says Meow!"

    def describe(self):
        return f"{self.color} cat named {self.name}"

cat = Cat("Whiskers", "orange")
print(cat.speak())      # Whiskers says Meow!
print(cat.describe())   # orange cat named Whiskers
inheritance super override parent
</> Dunder Methods

Magic/dunder methods for operator overloading and built-in behaviour.

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 __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2)    # Vector(6, 8)
print(v1 * 3)     # Vector(6, 9)
print(v1 == v2)   # False
dunder magic __add__ __repr__ operator
</> @property Decorator

Create managed attributes with getters, setters, and deleters.

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        """Getter for radius."""
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius cannot be negative")
        self._radius = value

    @property
    def area(self):
        """Computed property – no setter needed."""
        import math
        return math.pi * self._radius ** 2

c = Circle(5)
print(c.area)     # 78.539...
c.radius = 10
print(c.area)     # 314.159...
@property getter setter computed

Advanced Python (4 snippets)

Generators, context managers, exception handling, and advanced patterns.

</> Try / Except / Finally

Handle errors gracefully with exception handling blocks.

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print(f"Result: {result}")
except ValueError:
    print("That's not a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print("No errors occurred!")
finally:
    print("Execution complete.")
try except finally exception error
</> Generators & yield

Create memory-efficient iterators using yield instead of return.

# Generator function

def fibonacci(n):
    """Generate first n Fibonacci numbers."""
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Using the generator
for num in fibonacci(10):
    print(num, end=" ")
# 0 1 1 2 3 5 8 13 21 34

# Generator expression
squares = (x**2 for x in range(1000000))
print(next(squares))  # 0
print(next(squares))  # 1
yield generator iterator memory
</> Context Managers

Create custom context managers with __enter__ and __exit__.

# Custom context manager class
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        return self

    def __exit__(self, *args):
        import time
        elapsed = time.time() - self.start
        print(f"Elapsed: {elapsed:.4f}s")

with Timer():
    # Some work
    sum(range(10000000))

# Using contextlib
from contextlib import contextmanager
@contextmanager
def temp_dir():
    import tempfile, shutil, os
    dirpath = tempfile.mkdtemp()
    try:
        yield dirpath
    finally:
        shutil.rmtree(dirpath)
context manager __enter__ __exit__ contextlib
</> Type Hints (3.5+)

Add optional static type annotations for better code clarity.

from typing import List, Dict, Optional, Union

# Function with type hints
def greet(name: str, age: int) -> str:
    return f"{name} is {age} years old."

# Complex types
def process_items(
    items: List[int],
    mapping: Dict[str, float]
) -> Optional[Dict[str, Union[int, float]]]:
    if not items:
        return None
    return {str(k): float(v) for k, v in zip(items, mapping.values())}

# Variable annotation
count: int = 0
names: List[str] = ["Alice", "Bob"]
type hints typing Optional Union annotations

Built-in Functions (4 snippets)

Essential Python built-in functions: map, filter, zip, enumerate, sorted, and more.

</> map, filter, reduce

Functional programming tools for transforming and filtering iterables.

from functools import reduce

# map - apply function to each element
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)  # [2, 4, 6, 8, 10]

# filter - keep elements that pass test
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4]

# reduce - cumulative operation
product = reduce(lambda a, b: a * b, numbers)
print(product)  # 120 (factorial of 5)
map filter reduce functional
</> zip & enumerate

Combine iterables with zip and get index-value pairs with enumerate.

# zip - combine multiple iterables
names = ["Alice", "Bob", "Charlie"]
ages = [30, 25, 35]
for name, age in zip(names, ages):
    print(f"{name}: {age}")

# zip longest (itertools)
from itertools import zip_longest
for n, a in zip_longest(names, [30, 25], fillvalue="N/A"):
    print(n, a)

# enumerate - get index and value
for i, name in enumerate(names, start=1):
    print(f"{i}. {name}")
# 1. Alice  2. Bob  3. Charlie
zip enumerate combine index
</> sorted & reversed

Sort any iterable and reverse sequences with built-in functions.

# sorted - returns new sorted list
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_nums = sorted(numbers)
print(sorted_nums)  # [1, 1, 2, 3, 4, 5, 9]

# Custom sort key
words = ["banana", "apple", "cherry", "date"]
by_length = sorted(words, key=len)
print(by_length)  # ['date', 'apple', 'banana', 'cherry']

# Reverse sorting
reverse_nums = sorted(numbers, reverse=True)
print(reverse_nums)  # [9, 5, 4, 3, 2, 1, 1]

# reversed - returns iterator
for num in reversed(range(5)):
    print(num, end=" ")  # 4 3 2 1 0
sorted reversed sort key
</> any, all, min, max, sum

Quick aggregation and truth-testing over iterables.

values = [0, 1, 2, 3, 4]

# any - True if at least one is truthy
print(any(values))  # True (1 is truthy)
print(any([0, 0, 0]))  # False

# all - True if all are truthy
print(all(values))  # False (0 is falsy)
print(all([1, 2, 3]))  # True

# min, max, sum
print(min(values))  # 0
print(max(values))  # 4
print(sum(values))  # 10

# With custom key
words = ["cat", "elephant", "dog"]
print(min(words, key=len))  # cat
any all min max sum aggregation

Master Python Faster

Copy, paste, and adapt 50+ ready-to-use Python code snippets. From "Hello World" to decorators – we've got you covered.

No signup required. All snippets are free, tested, and work with Python 3.6+.

🐍 50+ Snippets
📋 One-Click Copy
🔍 Instant Search
✓ Variables & Types ✓ Loops & Conditions ✓ Functions & Lambdas ✓ OOP & Inheritance
Browse All Snippets

Frequently Asked Questions

A free, interactive reference with 50+ Python code snippets covering basics, control flow, functions, data structures, OOP, and advanced topics.
Absolutely! Each snippet has a "Copy" button – click it to copy the code directly to your clipboard.
Yes! It starts with basic syntax and progresses to advanced concepts. Great for both learning and quick reference.
All snippets are written for Python 3.6+. Some features like f-strings require 3.6+, and match/case requires 3.10+.
You can save this page (Ctrl+S / Cmd+S) for offline access. All code is embedded directly in the HTML.
We regularly review and update snippets to reflect best practices and new Python features.
No – this cheatsheet is completely free with no ads, no signup, and no paywalls.
We welcome suggestions! Contact us through FreeToolr to request additional Python snippets or topics.

Ready to level up your Python skills?

Bookmark this cheatsheet for quick reference – all snippets are free and always will be.

Stay Updated with FreeToolr

Get new AI tools, SEO resources, calculators, prompts and free templates delivered to your inbox. No spam, unsubscribe anytime.

Weekly Updates New Tool Alerts Free Resources

By subscribing, you agree to our Privacy Policy. No spam, ever.

Successfully Subscribed!

Thank you for joining the FreeToolr community. Check your inbox for a confirmation email.

500+
Free Online Tools
And growing weekly
500+
AI Powered Tools
ChatGPT, Claude & Gemini
300+
Free Guides & Tutorials
Learn by doing
50+
Tool Categories
Organized for you
100%
Completely Free
No hidden costs
No
Signup Required
Start instantly
500+ Free Tools
Millions of Users
Privacy Focused
No Registration
Works on Mobile
Fast Processing
Worldwide Access
Copyright © 2018-2026 FreeToolr. All rights reserved. Managed by Dotdunia Technologies
Made with for creators, developers, marketers and businesses.