Python Cheatsheet - Syntax, List, Dict & File Commands
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.
Typical Use Case
For developers writing scripts and doing data work in Python. This sheet puts the two things worth knowing best side by side: the engineering side of virtual environments (venv plus pip freeze, solving "works on my machine") and the language side of containers, comprehensions, file IO and exception handling. Exception handling deserves extra attention — with guarantees the file is closed, and finally guarantees cleanup always runs. Those two habits eliminate a large class of intermittent production problems.
Virtual Environment & Package Management 8
python3 -m venv venvsource venv/bin/activatevenv\Scripts\activatedeactivatepip install packagepip install -r requirements.txtpip freeze > requirements.txtpip listData Types 7
list = [1, 2, 3]tuple = (1, 2, 3)dict = {"key": "value"}set = {1, 2, 3}str = "hello"type(obj)isinstance(obj, int)List Comprehension 5
[x*2 for x in range(10)][x for x in range(10) if x % 2 == 0]{x: x*2 for x in range(5)}{x for x in range(10) if x % 2 == 0}list(map(lambda x: x*2, [1,2,3]))File I/O 8
with open("file.txt", "r") as f: content = f.read() lines = f.readlines()with open("file.txt", "w") as f: f.write("content")with open("file.txt", "a") as f:import json; json.load(f)json.dump(data, f, indent=2)Exception 8
try: result = 10 / 0except ZeroDivisionError as e: print(f"Error: {e}")except Exception as e:else:finally:raise ValueError("msg")Built-in 8
len(obj)range(start, stop, step)enumerate(iterable)zip(list1, list2)sorted(iterable, key=None, reverse=False)filter(func, iterable)map(func, iterable)any(iterable) / all(iterable)Parameter matrix
| Parameter | Effect | Example |
|---|---|---|
python3 -m venv venv | Create an isolated virtual environment so project packages never mix with system-wide ones. | python3 -m venv venv |
source venv/bin/activate | Activate that environment; the shell prompt is prefixed with (venv) while it is active. | source venv/bin/activate |
deactivate | Leave the virtual environment and fall back to the system Python interpreter. | deactivate |
pip install -r | Install every dependency listed in a requirements file in one pass. | pip install -r requirements.txt |
pip freeze | Export the exact resolved versions so a teammate can reproduce your environment. | pip freeze > requirements.txt |
list / dict / set | The three mutable built-ins: an ordered sequence, a key-value mapping, and an unordered deduplicated set. | dict = {"key": "value"} |
isinstance | Test whether an object has a given type, returning True for subclasses as well. | isinstance(obj, int) |
list comprehension | Filter and transform an iterable in a single expression, which usually beats a manual for loop. | [x*2 for x in range(10)] |
dict comprehension | Build a mapping straight from a sequence without a separate assignment loop. | {x: x*2 for x in range(5)} |
with open(...) as f | Scope the file handle to a block so it is closed on every path, including exceptions. | with open("file.txt") as f: |
try/except/else/finally | Four clauses with separate jobs: run risky code, handle failure, run on success, always clean up. | except ZeroDivisionError as e: |
enumerate / zip | Iterate with an index attached, or walk several sequences in lockstep without an index variable. | enumerate(iterable) |
map / filter / any / all | Functional building blocks for transforming a sequence and testing it in one expression. | sorted(x, key=lambda v: v[1], reverse=True) |
Common pitfalls
SymptomA package is clearly installed, yet importing it still raises ModuleNotFoundError.
CauseIt was installed into a different interpreter or a different virtual environment than the one running the script.
FixInstall with python -m pip install so pip and the interpreter match, confirm the venv is active with source venv/bin/activate, and check the resolved path with which python.
SymptomA script throws midway and the file is left open, so the next run reports that the file is in use.
CauseThe file was opened with f = open(...) instead of with, so close() is skipped when an exception unwinds the function.
FixAlways use with open("file.txt") as f: so the handle is closed when the block exits.
SymptomAfter except Exception the program keeps running silently and the real error disappears.
CauseThe handler only prints or is written as pass, so nothing is logged or re-raised.
FixCatch only what you can genuinely recover from; otherwise log it and re-raise, or at minimum keep the full traceback in the log.
SymptomAfter writing with open(f, "w") the previous contents of the file are gone.
CauseMode "w" truncates the file the moment it is opened, before a single byte is written.
FixUse "a" to append, and back the file up first or write to a temporary file and replace it when the original must be preserved.
Symptomrange is fine for length checks, but on older versions it materialises a full list and eats memory.
CauseIn Python 2 range builds the whole list eagerly; only Python 3 turned it into a lazy iterator.
FixOn Python 3 either range or xrange is fine; just confirm the project interpreter version so the two never get mixed.
SymptomReading a key that is not in the dictionary raises KeyError instead of returning a default.
CauseThe lookup uses d[key], which demands the key exist, rather than d.get(key).
FixUse d.get(key, default) for keys that may be missing, and combine d.get(key) is None with an in check when you must tell a missing key apart from a stored None.
SymptomThe pinned versions are correct on your machine, but a colleague cannot install them or gets different ones.
Causerequirements.txt was never committed, or the committed copy contains local private indexes and absolute paths from your own machine.
FixRun pip freeze > requirements.txt, delete the local path lines, then commit it and reproduce with pip install -r in CI.
Troubleshooting
1Confirm which interpreter is actually running
which python && python -V && python -m pip listRead all three together to immediately separate a wrong-environment problem from a version mismatch.
2Reproduce a teammate's dependency environment
python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txtCreate, activate, install from the file: these three steps are the standard reproduction path.
3Check whether a library really got installed
pip listWhen debugging a dependency conflict, look at the installed versions first and only then decide which one to pin.
4Read a file safely and handle the error path
with open("file.txt") as f: print(f.read())with guarantees the close even on failure; pair it with try/except around FileNotFoundError.
5Count entries and sort them by value
sorted(data, key=lambda x: x[1], reverse=True)sorted returns a new list and leaves the original untouched; the key can index a tuple or a dict key.
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.txtWindows 下激活改用 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