Programming Language
Updated for 2026

Python Cheatsheet & Interactive Cheat Sheet

Your complete Python cheatsheet and interactive cheat sheet. Learn basic commands, data structures (lists, dicts), OOP principles, and useful library methods.

Target Version Compatibility

Interactive Skill Mastery

Mark commands as learned to build your customized reference tracker. Retained locally in this browser.

Level:Novice
Command Mastery Progress0 of 20 Mastered (0%)

Basics

print("Hello, World!")
BeginnerBasics
Print specified text or variables directly to the standard output console.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

print("Hello, World!")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
name = input("Enter your name: ")
BeginnerBasics
Prompt the user for inputs from the terminal console and store it as a string.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

name = input("Enter your name: ")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
try:\n result = 10 / 0\nexcept ZeroDivisionError as e:\n print(f"Error: {e}")
BeginnerBasics
Gracefully catch and handle dynamic runtime exceptions to prevent program crashes.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

try:\n    result = 10 / 0\nexcept ZeroDivisionError as e:\n    print(f"Error: {e}")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)

Data Structures

items = [x**2 for x in range(10)]
BeginnerBasics
Create a list using a clean, one-line list comprehension loop with operations.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

items = [x**2 for x in range(10)]

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
my_dict = {"name": "Alice", "role": "Admin"}
BeginnerBasics
Define a dictionary key-value pair for highly optimized hash lookups.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

my_dict = {"name": "Alice", "role": "Admin"}

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
my_list.append("new_item")
BeginnerBasics
Insert an additional item at the absolute end of an existing list collection.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

my_list.append("new_item")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
val = my_dict.get("key", "default_val")
BeginnerBasics
Access dictionary keys safely with a default fallback value if the key does not exist.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

val = my_dict.get("key", "default_val")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
filtered = [x for x in items if x > 5]
IntermediateAdvanced
Create a subset list filtering elements dynamically using a conditional list comprehension.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

filtered = [x for x in items if x > 5]

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)

Functions

def greet(name, fallback="Guest"): return f"Hi {name}"
BeginnerBasics
Declare a function supporting custom parameter sets and default fallback values.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

def greet(name, fallback="Guest"): return f"Hi {name}"

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
def my_func(*args, **kwargs): print(args, kwargs)
BeginnerBasics
Declare functions accepting variable numbers of positional or keyword parameters.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

def my_func(*args, **kwargs): print(args, kwargs)

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
square = lambda x: x * x
BeginnerBasics
Create an anonymous lambda function for quick, single-line mathematical mappings or operations.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

square = lambda x: x * x

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
import asyncio\n\nasync def fetch():\n await asyncio.sleep(1)\n\nasync def main():\n await asyncio.gather(fetch(), fetch())
IntermediateTeam Workflow
Execute concurrent asynchronous operations and coroutines simultaneously with the asyncio engine.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

import asyncio\n\nasync def fetch():\n    await asyncio.sleep(1)\n\nasync def main():\n    await asyncio.gather(fetch(), fetch())

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
def debug_decorator(func):\n def wrapper(*args, **kwargs):\n print(f"Calling {func.__name__}")\n return func(*args, **kwargs)\n return wrapper
BeginnerBasics
Define custom function decorators to inject telemetry, caching, or logging wrappers dynamically.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

def debug_decorator(func):\n    def wrapper(*args, **kwargs):\n        print(f"Calling {func.__name__}")\n        return func(*args, **kwargs)\n    return wrapper

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)

OOP & Classes

class Dog(Animal):\n def __init__(self, name):\n super().__init__()\n self.name = name
BeginnerBasics
Declare custom object-oriented classes with constructor initialization and base-class inheritance.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

class Dog(Animal):\n    def __init__(self, name):\n        super().__init__()\n        self.name = name

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
from typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass Stack(Generic[T]):\n def __init__(self):\n self.items = []
BeginnerBasics
Establish static type-safe Generic class schemas using Python typing declarations.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

from typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass Stack(Generic[T]):\n    def __init__(self):\n        self.items = []

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
class MetaSingleton(type):\n _instances = {}\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super().__call__(*args, **kwargs)\n return cls._instances[cls]
BeginnerBasics
Construct a customized metaclass to control class creations (e.g. enforcing strict Singleton design patterns).

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

class MetaSingleton(type):\n    _instances = {}\n    def __call__(cls, *args, **kwargs):\n        if cls not in cls._instances:\n            cls._instances[cls] = super().__call__(*args, **kwargs)\n        return cls._instances[cls]

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)

File & I/O

with open("data.txt", "r") as file:\n content = file.read()
BeginnerBasics
Open a file safely under an automated file close/cleanup resource context.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

with open("data.txt", "r") as file:\n    content = file.read()

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
import json\ndata = json.loads(json_str)
BeginnerBasics
Parse standard JSON-formatted string datasets into local Python dictionaries.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

import json\ndata = json.loads(json_str)

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
import os\ncurrent_dir = os.getcwd()
BeginnerBasics
Import the core OS library to retrieve current workspace directories or interact with the filesystem.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

import os\ncurrent_dir = os.getcwd()

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)
from contextlib import contextmanager\n\n@contextmanager\ndef managed_resource():\n print("Setup")\n yield "Resource"\n print("Teardown")
BeginnerBasics
Create a custom helper context manager using yield-generator semantics instead of writing class-level __enter__ / __exit__.

When to Use

When writing Python scripts, logic controllers, backend services, or standard terminal utility tasks.

Common Mistakes

Mixing up indentation types (tabs versus spaces) or ignoring local virtual packages isolated inside standard virtualenvs.

Shortcut / Pro-Tip

Use virtual environments (python -m venv .venv) to fully isolate workspace dependencies on local machines.

Example

from contextlib import contextmanager\n\n@contextmanager\ndef managed_resource():\n    print("Setup")\n    yield "Resource"\n    print("Teardown")

Output Example

Console / Terminal
Success (Command executed on active Python 3.x runtime environments)

Python Best Practices

1Use Visual PEP 8 Style Rules

Write clean, readable Python code adhering to standard PEP 8 guide recommendations (use 4 spaces per indent level).

2Always Setup Virtualenv Sandboxes

Never install packages globally. Keep developer library versions isolated with venv or pipenv cheat sheet configurations.

3Leverage Modern List Comprehensions

Keep standard loops clean and highly optimized by replacing verbose loops with concise Python list comprehensions.

4Utilize Context Managers for File Buffers

Always open system descriptors using the 'with' keyword, avoiding manual close calls and memory leak concerns.

5Format Strings with Modern F-Strings

Use f-string syntax (e.g. f'Hello {name}') which executes significantly faster and is much cleaner than old % or .format() syntaxes.

Common Python Errors & Solutions

Error

IndentationError: unexpected indent

Solution

Check that your script does not mix spaces and tabs. Standardize on 4 spaces for all indentations.

Error

TypeError: 'list' object is not callable

Solution

You likely used the name of a built-in function (like 'list') as a variable name. Rename the local variable to free the function reference.

Error

KeyError: 'item_not_found'

Solution

Attempting to access a dictionary key that doesn't exist. Solution: Use the safe dictionary method: my_dict.get('item_not_found', default_fallback) instead.

Error

NameError: name 'x' is not defined

Solution

You are trying to access a variable before assigning a value, or accessing it outside its active local/global scope.

Error

ModuleNotFoundError: No module named 'x'

Solution

Run 'pip install x' within your active virtualenv environment directory to download the missing dependency.

Common Python Interview Questions

Q1How do you define list comprehensions in Python, and when should you use them?

A list comprehension provides a concise syntax to create lists based on existing lists. Syntax: [expression for item in iterable if condition]. Use it to keep code readable and concise, but avoid multi-nested comprehensions that hurt readability.

Q2What is the difference between Python lists and tuples?

Python lists are mutable collections declared with square brackets [], meaning their values can change. Tuples are immutable sequence structures declared with parentheses (), making them faster, memory-efficient, and suitable for dictionary keys.

Q3Explain the difference between deep copy and shallow copy in Python.

A shallow copy creates a new object container but copies references to the nested child objects. A deep copy recursively copies the container as well as all nested objects, meaning modifications on one copy never affect the other.

Q4What are Python decorators and how do they work?

Decorators are wrapper functions that dynamically extend or modify the runtime behavior of another target function without changing its internal source code structure. They take a function as an argument and return a modified wrapper.

Q5How does memory management work under Python?

Python utilizes automatic private heap storage memory management. It is governed by reference counting (allocations/deallocations based on active pointers) and an integrated generational garbage collector to resolve circular references.