Python CheatSheet

The purpose of this Python cheat sheet is to assist students in rapidly reviewing important ideas, syntax, and best practices in one location. This guide offers clear examples and succinct explanations to save time and increase productivity, whether you're a newbie looking for a quick reference, getting ready for a Python interview, or searching for a thorough PDF cheat sheet.

Python Syntax & Structure

Overview

Syntax of Python has readability and simplicity as it uses indentation to define code blocks

Zen of Python (Python Enhancement Proposal 20)

  • Readability counts
  • Explicit is better than implicit
  • Simple is better than complex
  • Errors should never pass silently
  • Practicality beats purity
import this

Python Versions: Python 2 vs Python 3

FeaturePython 2Python 3 (3.12 focus)
StatusEnd-of-lifeActively maintained
StringsASCII by defaultUnicode by default
Division5 / 2 == 25 / 2 == 2.5
PrintStatementFunction
IntegersFixed-size intArbitrary precision
UnicodeManualNative

Interview Tip

Python is compiled AND interpreted and not purely interpreted.

How Python Actually Works

#how python works
1.
Source code (.py) 2. Compiled to bytecode (.pyc) 3. Executed by Python Virtual Machine (PVM)
#how C / C++  works
1.
Source code 2. Executed directly on hardware 3. No compilation

Interpreted vs Compiled Languages

AspectPythonC / C++
CompilationBytecodeMachine code
ExecutionVirtual MachineDirect hardware
PortabilityHighPlatform-dependent
SpeedSlowerFaster

Keywords

importdefifforwhilereturn

1.2 Syntax & Structure

Overview

Python indentation rules, comments, docstrings, keywords, identifiers, and naming conventions as expected in interviews.

Indentation & Whitespace Rules

  • Indentation defines code blocks
  • 4 spaces per level (PEP 8)
  • Tabs and spaces should not be mixed
if x > 0:
    print("Positive")
else:
    print("Not positive")

Indentation: Correct vs Incorrect

if x > 0:
    print(x)
if x > 0:
print(x)  # IndentationError

Interview Tip

Python enforces indentation to improve readability and avoid ambiguous blocks.

Comments & Docstrings

  • Single-line comments start with #
  • Inline comments are written after code
  • Docstrings use triple quotes and document APIs
def add(a, b):
    """
    Returns the sum of two numbers.
    """
    return a + b

Comments vs Docstrings

FeatureCommentDocstring
PurposeExplain codeDocument API
Runtime Access✅ (__doc__)
Style#Triple quotes

Interview Tip

Docstrings are used by tools like help() and documentation generators such as Sphinx.

Python Keywords

ifelseforwhiledefclassmatchyieldimport

Identifier Naming Conventions (PEP 8)

TypeConvention
Variablesnake_case
Functionsnake_case
ClassPascalCase
ConstantUPPER_CASE

1.3 Data Types & Expressions

Overview

Data items needs to classified so we use data types for it. Combinations of values, variables and operators are called expressions which produce a result.

Statements vs Expressions

TermDescription
StatementPerforms an action
ExpressionProduces a value

Expression Example

  • Python favors expressions over statements
result = "yes" if x > 0 else "no"

Numeric Type Comparison

TypeMutablePrecisionCommon Use
intExactCounters, IDs
floatApproximateMeasurements
complexExactMath

Interview Tip

Python integers have arbitrary precision and do not overflow like C/C++ integers.

Boolean Type

  • True and False are boolean values
  • bool is a subclass of int
  • Implicit truthiness is preferred
isinstance(True, int)  # True

Text Type: str

  • Strings are immutable
  • Unicode by default in Python 3
s = "Python"
s[0]  # 'P'
s[-1] # 'n'

None Type

  • Represents absence of value
  • Singleton object
  • Use 'is None' for comparison
x = None
x is None  # ✔ preferred

Type Checking

MethodNotes
type()Strict, rarely recommended
isinstance()Supports inheritance, preferred

1.4 Variables & Assignment

Overview

A name for container which stores data like numbers, integers in computer memory is called a variable. Assignment is the process of giving that variable a value using the = symbol

Variable Naming Rules

  • Identifiers must start with a letter or underscore
  • Cannot use Python keywords as names
user_name = "Alice"
_private = 42

Naming Conventions (PEP 8)

ElementConvention
Variablesnake_case
ConstantUPPER_CASE
ClassPascalCase

Dynamic Typing

  • Variables can change type
  • Type checking happens at runtime
  • Python is strongly typed
x = 10
x = "now a string"

Interview Tip

Python is strongly typed, not weakly typed.

Multiple Assignment & Unpacking

  • Assign multiple variables at once
  • Swap variables without temporary variables
a, b = 1, 2
a, b = b, a
x, *rest = [1, 2, 3, 4]

Constants

Constants are not enforced in Python. Uppercase naming signals intent.

2.1 Sequences

Overview

Sequences in Python include lists, tuples, and ranges. They support indexing, slicing, and iteration.

Lists

  • Ordered collection
  • Mutable
  • Heterogeneous elements allowed
lst = [1, 2, 3]
lst.append(4)

List Complexity

OperationTime
AppendO(1)*
InsertO(n)
LookupO(1)

Tuples

  • Immutable
  • Hashable if elements are hashable
  • Faster than lists
t = (1, 2, 3)

Interview Use

Tuples are commonly used as dictionary keys and for returning multiple values from functions.

Ranges

  • Lazy sequence
  • Memory efficient
range(0, 10, 2)

Indexing & Slicing

  • Supports positive and negative indexing
  • Slicing creates a new object
lst[1]
lst[-1]
lst[1:4]
lst[::-1]

Mutability Comparison

TypeMutable
list
tuple
range
str

2.2 Sets

Overview

Sets are unordered collections of unique elements optimized for fast membership testing and set operations.

Set Creation

  • Stores unique elements
  • Unordered collection
s = {1, 2, 3}
empty = set()  # {} creates a dict

Set Operations

  • Union, intersection, difference, symmetric difference
a | b   # union
a & b   # intersection
a - b   # difference
a ^ b   # symmetric difference

Frozen Sets

  • Immutable
  • Hashable
  • Can be dictionary keys
fs = frozenset([1, 2, 3])

2.3 Dictionaries

Overview

Dictionaries store key–value pairs and provide fast lookups using hash tables.

Key–Value Pairs

  • Ordered in Python 3.7+
  • Fast lookups
d = {"a": 1, "b": 2}

Hashability Rules

  • Keys must be hashable
  • Lists, dicts, and sets cannot be keys
# Valid: int, str, tuple
# Invalid: list, dict, set

Dictionary Methods

  • Access keys, values, and items
  • Safely retrieve values with defaults
d.keys()
d.values()
d.items()
d.get("a", 0)
d.pop("a")

Nested Dictionaries

  • Values can themselves be dictionaries
users = {
    "u1": {"age": 20, "active": True}
}

Interview Tip

Always access dictionary values safely using .get() to avoid KeyError.

2.4 Strings

Overview

String in Python are immutable sequence of Unicode characters used for storing and manipulating text data

Common String Methods

  • Strings are immutable
  • Provide rich built-in methods
s.lower()
s.upper()
s.strip()
s.replace("a", "b")
s.split(",")

String Formatting

  • f-strings are preferred
  • format() is still supported
name = "Ada"
age = 30
f"{name} is {age}"
"{:.2f}".format(3.14159)

Formatting Comparison

MethodSpeedReadability
f-string⭐⭐⭐⭐⭐⭐
format()⭐⭐⭐⭐

Encoding & Unicode

  • Strings are Unicode
  • Bytes represent encoded data
text = "café"
encoded = text.encode("utf-8")
decoded = encoded.decode("utf-8")

Regular Expressions (Intro)

  • Used for validation, parsing, and pattern searching
import re
re.search(r"\d+", "abc123")
re.findall(r"\w+", "hello world")

Quick Complexity Reference

StructureLookupInsert
ListO(1)O(n)
TupleO(1)
SetO(1)O(1)
DictO(1)O(1)

3.1 Conditional Logic

Overview

Conditional logic in Python allows branching execution using if/elif/else, boolean logic, ternary expressions, and pattern matching.

if / elif / else

  • Conditions evaluated top-down
  • First matching block executes
  • No switch-case before Python 3.10
if x > 0:
    result = "positive"
elif x == 0:
    result = "zero"
else:
    result = "negative"

Boolean Logic

  • Supports and, or, not operators
  • Uses short-circuit evaluation
x and func()   # func() runs only if x is truthy
x or default   # returns first truthy value

Interview Tip

and / or return operands themselves, not True or False.

Ternary Expressions

  • Expression, not a statement
  • Useful for simple conditions
  • Avoid nesting for readability
status = "adult" if age >= 18 else "minor"

Pattern Matching (Python 3.10+)

  • More powerful than switch-case
  • Supports destructuring and guards
match value:
    case 1:
        print("one")
    case 2 | 3:
        print("two or three")
    case _:
        print("default")

Pattern Matching (Advanced)

  • Supports tuple unpacking
match point:
    case (0, 0):
        print("origin")
    case (x, y):
        print(x, y)

Interview Tip

Pattern matching is not just switch-case; it supports structural matching and destructuring.

3.2 Loops

Overview

Loops in Python are used for iteration over iterables and repeated execution using for and while loops.

for Loops

  • Iterates directly over iterables
  • Does not rely on index implicitly
for i in range(5):
    print(i)

while Loops

  • Condition checked before each iteration
  • Risk of infinite loops if condition never changes
while condition:
    do_something()

Loop Control Statements

KeywordPurpose
breakExit loop
continueSkip iteration
passPlaceholder

Loop Control Example

  • Use break and continue to control flow
for i in range(5):
    if i == 2:
        continue
    if i == 4:
        break

Nested Loops

  • Loops can be nested
  • Often result in O(n²) complexity
for i in range(3):
    for j in range(2):
        print(i, j)

else with Loops

  • Executes only if loop does not break
  • Common interview question
for x in nums:
    if x == target:
        break
else:
    print("Not found")

3.3 Iteration Tools

Overview

Python provides built-in tools like range, enumerate, and zip to simplify iteration and improve readability.

range()

  • Lazy sequence
  • Uses constant memory
range(5)
range(1, 10, 2)

enumerate()

  • Provides index and value pairs
  • Preferred over manual indexing
for index, value in enumerate(items):
    print(index, value)

zip()

  • Iterates over multiple iterables
  • Stops at the shortest iterable
for a, b in zip(list1, list2):
    print(a, b)

Python 3.10+

zip(strict=True) raises an error if iterables have different lengths.

Iterables vs Iterators

ConceptDefinition
IterableCan be looped over
IteratorProduces next value

Iterator Example

  • Iterators are exhausted after use
it = iter([1, 2, 3])
next(it)

Interview Tip

Once exhausted, an iterator cannot be reused unless recreated.

4.1 Function Basics

Overview

This section introduces defining, calling, and returning values from functions, along with core terminology.

Defining & Calling Functions

  • Functions are defined using def
  • Functions can return values
def greet(name):
    return f"Hello {name}"

greet("Alice")

Parameters vs Arguments

TermMeaning
ParameterVariable in function definition
ArgumentValue passed to function

Return Values

  • Functions return None implicitly
  • Multiple values are returned as a tuple
def f():
    return 1, 2

a, b = f()

4.2 Advanced Function Concepts

Overview

Default arguments are parameters that, if they are not supplied, have a predetermined value. Parameters that must be passed using their name are known as keyword-only arguments. A function can take any number of arguments thanks to variable-length arguments.

Default Arguments

  • Default values evaluated once at definition time
def add(x, y=10):
    return x + y

Mutable Default Argument Pitfall

def good(x=None):
    if x is None:
        x = []
def bad(x=[]):
    x.append(1)

Keyword-Only Arguments

  • Improves readability
  • Prevents misuse of arguments
def func(a, *, b):
    return a + b

Variable-Length Arguments

  • *args collects positional arguments
  • **kwargs collects keyword arguments
def f(*args, **kwargs):
    print(args)
    print(kwargs)

Docstrings

  • Used by help()
  • Essential for APIs and libraries
def add(a, b):
    """Return the sum of a and b."""
    return a + b

4.3 Functional Programming Tools

Overview

Lambda functions, map, filter, reduce, and comprehensions are some of the tools that Python uses to support functional-style programming. One line can be used to write small, anonymous functions thanks to lambda functions. While filter() chooses elements based on a condition, map() applies a given function to every element of an iterable. The reduce() function creates a single result by repeatedly combining elements. By applying expressions and conditions to iterables, comprehensions offer a clear and readable method of creating new collections.

Lambda Functions

  • Anonymous functions
  • Single expression only
  • Avoid complex lambdas
square = lambda x: x * x

map(), filter(), reduce()

  • Operate on iterables
  • Functional-style transformations
map(lambda x: x*2, nums)
filter(lambda x: x > 0, nums)

from functools import reduce
reduce(lambda a, b: a + b, nums)

Interview Tip

Prefer comprehensions over map/filter for better readability.

Comprehensions

  • Concise and readable
  • Considered Pythonic
[x*x for x in range(5)]
{x for x in nums if x > 0}
{k: v for k, v in pairs}

map/filter vs Comprehensions

ToolReadabilityPythonic
map/filter⭐⭐⭐⭐
Comprehensions⭐⭐⭐⭐⭐⭐

Time Complexity Highlights

ConstructComplexity
Single loopO(n)
Nested loopsO(n²)
ComprehensionSame as loop

5.1 Exceptions

Overview

Exceptions in Python are used to handle runtime errors gracefully and separate error-handling logic from normal program flow.

Built-in Exceptions (Common & Interview-Relevant)

ExceptionRaised When
TypeErrorWrong type operation
ValueErrorCorrect type, invalid value
IndexErrorSequence index out of range
KeyErrorDictionary key missing
AttributeErrorAttribute not found
ZeroDivisionErrorDivision by zero
FileNotFoundErrorFile does not exist
ImportErrorImport failure

Interview Tip

Know when to use TypeError versus ValueError.

try / except / else / finally

  • else runs only if no exception occurs
  • finally always runs for cleanup
try:
    x = int("10")
except ValueError:
    print("Conversion failed")
else:
    print("Success:", x)
finally:
    print("Always runs")

Exception Handling: Bad vs Good

try:
    risky()
except ValueError as e:
    print(e)
try:
    risky()
except:
    pass  # Swallows all errors

Catching Multiple Exceptions

  • Use a tuple to catch multiple exception types
try:
    risky()
except (TypeError, ValueError) as e:
    print(e)

Raising Exceptions

  • Use raise to signal exceptional conditions
if age < 0:
    raise ValueError("Age cannot be negative")

Interview Tip

Use exceptions for exceptional cases, not normal control flow.

6.1 Classes & Objects

Overview

Classes and objects are the foundation of object-oriented programming in Python, combining data and behavior.

Class Definition

  • Classes define object blueprints
  • __init__ initializes object state
class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return f"Hello, {self.name}"

p = Person("Alice")
p.greet()

Attributes & Methods

TypeExample
Instance attributeself.name
Methoddef greet(self)
Class attributeDefined at class level

__init__ Constructor

  • Called automatically on object creation
  • Initializes object state
  • Forgetting self is a common mistake
def __init__(self, value):
    self.value = value

6.2 OOP Principles

Overview

Python supports core object-oriented principles such as encapsulation, inheritance, polymorphism, and abstraction.

Encapsulation

  • _var indicates internal use
  • __var triggers name mangling
  • Access control is based on convention
class Account:
    def __init__(self, balance):
        self._balance = balance

Interview Tip

Python relies on naming conventions rather than strict access modifiers.

Inheritance

  • Child classes can override parent behavior
  • Supports multiple inheritance
class Animal:
    def speak(self):
        pass

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

Polymorphism

  • Same interface, different behavior
  • Duck typing is common in Python
def make_sound(animal):
    return animal.speak()

Abstraction

  • Defines required interface
  • Abstract classes cannot be instantiated
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

6.3 Advanced OOP

Overview

Python's advanced object-oriented programming (OOP) features data classes, magic methods, and best practices for design. Magic methods, also known as dunder methods, allow objects to support built-in behaviours like operator overloading, comparison, and iteration. By automatically creating methods like __init__, __repr__, and __eq__, data classes make the process of creating classes easier. Writing clear, maintainable code using concepts like encapsulation, modularity, and the SOLID guidelines is the main goal of design best practices.

Magic (Dunder) Methods

MethodPurpose
__str__User-friendly string
__repr__Developer/debug string
__eq__Equality comparison
__len__Length
__call__Callable objects

Magic Method Example

  • __repr__ helps debugging
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

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

Data Classes (Python 3.7+)

  • Automatically generates boilerplate code
  • Best suited for data containers
from dataclasses import dataclass

@dataclass
class User:
    name: str
    age: int

Design Tips

ConceptUse When
ClassBehavior + state
Data classMostly data
InheritanceShared behavior
CompositionFlexible design
Abstract classEnforced interface