Python Cheatsheet - Command Reference

This reference is for developers who are new to Python or hop between projects, covering the syntax you reach for most when scripting, processing text and data, and automating small tasks. Unlike API listings, entries are grouped by real usage scenarios (environments, containers, file I/O, exceptions) so you can code directly. By the end you should be able to set up a venv, condense loops into comprehensions, read and write files and JSON safely, and contain runtime errors with try/except.

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

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

Typical Use Case

For developers whose day job revolves around scripting and data processing: scaffold a fresh venv and install dependencies, compress tedious loops into comprehensions, clean CSV or log lines by field, and persist intermediate results with with + json. Whether patching together a scratch tool, running a one-off report, or writing a scheduled task, these are the commands reused most.

Command Examples

Generate an arithmetically spaced sequence in one line

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

range(stop) 是左闭右开,stopping 值不包含;要从 1 数到 10 请写 range(1, 11)。

Output

[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Read and write a JSON file

import json with open("data.json", "r", encoding="utf-8") as f: data = json.load(f) with open("out.json", "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2)

ensure_ascii=False 才会保留中文可读,否则非 ASCII 字符会被写成 \uXXXX 转义;with 语句保证文件在出错或正常结束时都被正确关闭。

Read a traceback to find the exception source

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

先用精确的异常类型,等真正需要兜底时再用 except Exception 捕获,避免吞掉不该忽略的 KeyboardInterrupt。

Output

Error: division by zero

Create a virtual environment and install dependencies

python3 -m venv venv source venv/bin/activate pip install requests pip freeze > requirements.txt

Windows 下激活改用 venv\Scripts\activate;requirements.txt 应在每次添加依赖后重新导出保持一致。

Output

(venv) $

Common Pitfalls

  • Do not install packages into system Python blindly: test against venv before applying someone else's requirements.txt to avoid polluting or conflicting with the system interpreter.
  • range() is half-open (excludes the stop value); index off-by-one errors are the most common pitfall. Start from 1 with range(1, n + 1).
  • Using open() outside a with block without closing, or overlooking that mode="w" truncates the file first, can destroy data — confirm the path and mode before writing.
  • A bare except Exception also swallows KeyboardInterrupt (Ctrl+C); do not silence every error, log it or re-raise at least part of it.

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.

FAQ

Is a virtual environment mandatory for Python?

Not strictly, but strongly recommended. pip install writes into the global site-packages by default, so multiple projects can conflict. Create an isolated environment with python -m venv .venv and activate it before installing dependencies to keep them project-local.

What is the difference between == and is in Python?

== compares whether two objects are equal in value; is compares whether two variables refer to the same object in memory. Results may coincide for small numbers and interned strings, but for mutable containers like list and dict, is is usually False — use == for value equality and is only for object identity or None checks.

List comprehension or generator expression — which should I use?

They share the same syntax; a generator just swaps the outer brackets for parentheses. A list comprehension builds the whole list eagerly in memory, good when results are traversed repeatedly or sliced; a generator yields items lazily, saving memory, ideal for a single pass over huge data or aggregations like sum/min/max.

Why is with open() recommended, and what happens if I forget to close a file?

with open(path) as f automatically calls f.close() when the block ends, even on exceptions, so the handle is never leaked. Manually calling open() without close() can leave the file locked and buffers unflushed — prefer with, and if managing manually always close in a finally block.

Should I catch every exception in Python?

A bare except that swallows everything is harmful because it hides real bugs. Catch specific types (ValueError, KeyError) or at least except Exception, then re-raise or log afterwards so failures stay visible and debuggable.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us