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.

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

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 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

Parameter matrix

ParameterEffectExample
python3 -m venv venvCreate an isolated virtual environment so project packages never mix with system-wide ones.python3 -m venv venv
source venv/bin/activateActivate that environment; the shell prompt is prefixed with (venv) while it is active.source venv/bin/activate
deactivateLeave the virtual environment and fall back to the system Python interpreter.deactivate
pip install -rInstall every dependency listed in a requirements file in one pass.pip install -r requirements.txt
pip freezeExport the exact resolved versions so a teammate can reproduce your environment.pip freeze > requirements.txt
list / dict / setThe three mutable built-ins: an ordered sequence, a key-value mapping, and an unordered deduplicated set.dict = {"key": "value"}
isinstanceTest whether an object has a given type, returning True for subclasses as well.isinstance(obj, int)
list comprehensionFilter and transform an iterable in a single expression, which usually beats a manual for loop.[x*2 for x in range(10)]
dict comprehensionBuild a mapping straight from a sequence without a separate assignment loop.{x: x*2 for x in range(5)}
with open(...) as fScope the file handle to a block so it is closed on every path, including exceptions.with open("file.txt") as f:
try/except/else/finallyFour clauses with separate jobs: run risky code, handle failure, run on success, always clean up.except ZeroDivisionError as e:
enumerate / zipIterate with an index attached, or walk several sequences in lockstep without an index variable.enumerate(iterable)
map / filter / any / allFunctional 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

  1. 1Confirm which interpreter is actually running

    which python && python -V && python -m pip list

    Read all three together to immediately separate a wrong-environment problem from a version mismatch.

  2. 2Reproduce a teammate's dependency environment

    python3 -m venv venv && source venv/bin/activate && pip install -r requirements.txt

    Create, activate, install from the file: these three steps are the standard reproduction path.

  3. 3Check whether a library really got installed

    pip list

    When debugging a dependency conflict, look at the installed versions first and only then decide which one to pin.

  4. 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.

  5. 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.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