Python Cheatsheet - Command Reference

All the Python syntax you need for daily development — from basics to advanced features, organized by category, ready to copy into your code.

Languages·44 commands·Last updated 2026-07-21
Back to Languages

Virtual Environment & Package Management 8

python3 -m venv venv
Create a virtual environment
source venv/bin/activate
Activate virtual environment (Linux/Mac)
venv\Scripts\activate
Activate virtual environment (Windows)
deactivate
Deactivate virtual environment
pip install package
Install a package
pip install -r requirements.txt
Install dependencies from file
pip freeze > requirements.txt
Export current environment dependencies
pip list
List installed packages

Data Types 7

list = [1, 2, 3]
List, mutable ordered sequence
tuple = (1, 2, 3)
Tuple, immutable ordered sequence
dict = {"key": "value"}
Dictionary, key-value pairs
set = {1, 2, 3}
Set, unordered unique elements
str = "hello"
String, immutable sequence
type(obj)
Check object type
isinstance(obj, int)
Check if object is an instance of a type

List Comprehension 5

[x*2 for x in range(10)]
Basic list comprehension
[x for x in range(10) if x % 2 == 0]
List comprehension with condition
{x: x*2 for x in range(5)}
Dictionary comprehension
{x for x in range(10) if x % 2 == 0}
Set comprehension
list(map(lambda x: x*2, [1,2,3]))
Functional equivalent of comprehension

File I/O 8

with open("file.txt", "r") as f:
Read file (recommended with auto-close)
content = f.read()
Read all content
lines = f.readlines()
Read all lines into a list
with open("file.txt", "w") as f:
Write file (overwrite)
f.write("content")
Write string
with open("file.txt", "a") as f:
Append mode
import json; json.load(f)
Read JSON file
json.dump(data, f, indent=2)
Write JSON file

Exception 8

try:
Attempt to execute code
result = 10 / 0
Code that may raise an exception
except ZeroDivisionError as e:
Catch a specific exception
print(f"Error: {e}")
Handle exception
except Exception as e:
Catch all exceptions (fallback)
else:
Execute when no exception
finally:
Always execute regardless of exception
raise ValueError("msg")
Raise an exception explicitly

Built-in 8

len(obj)
Return object length
range(start, stop, step)
Generate integer sequence
enumerate(iterable)
Return index-value tuples
zip(list1, list2)
Zip multiple lists into tuples
sorted(iterable, key=None, reverse=False)
Sort
filter(func, iterable)
Filter elements
map(func, iterable)
Apply function to each element
any(iterable) / all(iterable)
Check if any/all are truthy

💡 Tips

  • Always use the with statement for file operations to ensure proper closing, even on exceptions.
  • List comprehensions are more concise and efficient than for loops, but use regular loops for complex logic.
  • In Python 3, range() returns an iterator, not a list — saving memory.