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 thisPython Versions: Python 2 vs Python 3
| Feature | Python 2 | Python 3 (3.12 focus) |
|---|---|---|
| Status | End-of-life | Actively maintained |
| Strings | ASCII by default | Unicode by default |
| Division | 5 / 2 == 2 | 5 / 2 == 2.5 |
| Statement | Function | |
| Integers | Fixed-size int | Arbitrary precision |
| Unicode | Manual | Native |
Interview Tip
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
| Aspect | Python | C / C++ |
|---|---|---|
| Compilation | Bytecode | Machine code |
| Execution | Virtual Machine | Direct hardware |
| Portability | High | Platform-dependent |
| Speed | Slower | Faster |
Keywords
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
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 + bComments vs Docstrings
| Feature | Comment | Docstring |
|---|---|---|
| Purpose | Explain code | Document API |
| Runtime Access | ❌ | ✅ (__doc__) |
| Style | # | Triple quotes |
Interview Tip
Python Keywords
Identifier Naming Conventions (PEP 8)
| Type | Convention |
|---|---|
| Variable | snake_case |
| Function | snake_case |
| Class | PascalCase |
| Constant | UPPER_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
| Term | Description |
|---|---|
| Statement | Performs an action |
| Expression | Produces a value |
Expression Example
- Python favors expressions over statements
result = "yes" if x > 0 else "no"Numeric Type Comparison
| Type | Mutable | Precision | Common Use |
|---|---|---|---|
| int | ❌ | Exact | Counters, IDs |
| float | ❌ | Approximate | Measurements |
| complex | ❌ | Exact | Math |
Interview Tip
Boolean Type
- True and False are boolean values
- bool is a subclass of int
- Implicit truthiness is preferred
isinstance(True, int) # TrueText 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 # ✔ preferredType Checking
| Method | Notes |
|---|---|
| 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 = 42Naming Conventions (PEP 8)
| Element | Convention |
|---|---|
| Variable | snake_case |
| Constant | UPPER_CASE |
| Class | PascalCase |
Dynamic Typing
- Variables can change type
- Type checking happens at runtime
- Python is strongly typed
x = 10
x = "now a string"Interview Tip
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
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
| Operation | Time |
|---|---|
| Append | O(1)* |
| Insert | O(n) |
| Lookup | O(1) |
Tuples
- Immutable
- Hashable if elements are hashable
- Faster than lists
t = (1, 2, 3)Interview Use
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
| Type | Mutable |
|---|---|
| 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 dictSet Operations
- Union, intersection, difference, symmetric difference
a | b # union
a & b # intersection
a - b # difference
a ^ b # symmetric differenceFrozen 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, setDictionary 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
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
| Method | Speed | Readability |
|---|---|---|
| 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
| Structure | Lookup | Insert |
|---|---|---|
| List | O(1) | O(n) |
| Tuple | O(1) | ❌ |
| Set | O(1) | O(1) |
| Dict | O(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 valueInterview Tip
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
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
| Keyword | Purpose |
|---|---|
| break | Exit loop |
| continue | Skip iteration |
| pass | Placeholder |
Loop Control Example
- Use break and continue to control flow
for i in range(5):
if i == 2:
continue
if i == 4:
breakNested 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+
Iterables vs Iterators
| Concept | Definition |
|---|---|
| Iterable | Can be looped over |
| Iterator | Produces next value |
Iterator Example
- Iterators are exhausted after use
it = iter([1, 2, 3])
next(it)Interview Tip
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
| Term | Meaning |
|---|---|
| Parameter | Variable in function definition |
| Argument | Value 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 + yMutable 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 + bVariable-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 + b4.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 * xmap(), 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
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
| Tool | Readability | Pythonic |
|---|---|---|
| map/filter | ⭐⭐ | ⭐⭐ |
| Comprehensions | ⭐⭐⭐ | ⭐⭐⭐ |
Time Complexity Highlights
| Construct | Complexity |
|---|---|
| Single loop | O(n) |
| Nested loops | O(n²) |
| Comprehension | Same 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)
| Exception | Raised When |
|---|---|
| TypeError | Wrong type operation |
| ValueError | Correct type, invalid value |
| IndexError | Sequence index out of range |
| KeyError | Dictionary key missing |
| AttributeError | Attribute not found |
| ZeroDivisionError | Division by zero |
| FileNotFoundError | File does not exist |
| ImportError | Import failure |
Interview Tip
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
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
| Type | Example |
|---|---|
| Instance attribute | self.name |
| Method | def greet(self) |
| Class attribute | Defined 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 = value6.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 = balanceInterview Tip
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):
pass6.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
| Method | Purpose |
|---|---|
| __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: intDesign Tips
| Concept | Use When |
|---|---|
| Class | Behavior + state |
| Data class | Mostly data |
| Inheritance | Shared behavior |
| Composition | Flexible design |
| Abstract class | Enforced interface |
