Python Cheatsheet

Search and filter 70+ Python 3 snippets by category. Click any card to copy the code instantly.

Showing 71 of 71 snippets — click any card to copy

Frequently Asked Questions

What is the difference between Python 2 and Python 3?

Python 3 (released 2008, Python 2 EOL in 2020) introduced breaking changes that make code cleaner and more consistent. Key differences: print is a function (not a statement), integer division always returns float with /, strings are Unicode by default, range() returns an iterator instead of a list, and there are many standard library improvements. All new projects should use Python 3.

How do list comprehensions improve performance?

List comprehensions are generally 10–50% faster than equivalent for-loop + append() patterns because they are optimised at the bytecode level — Python pre-allocates a list and appends in a tight C loop, avoiding per-iteration function call overhead. Generator expressions (round brackets instead of square) are even more memory-efficient for large sequences because they yield values lazily rather than building the entire list in memory.

What are Python decorators used for?

Decorators are higher-order functions that wrap another function to add behaviour without modifying its source code. Common use cases include: adding logging or timing, caching return values (@functools.lru_cache), enforcing access control, retrying on failure, validating arguments, and registering functions (e.g., Flask route decorators). They are syntactic sugar for the pattern func = decorator(func).

What is the difference between __repr__ and __str__?

__repr__ is meant for developers — it should return an unambiguous string that could ideally be used to recreate the object (e.g., Point(x=1, y=2)). __str__ is for end users and should be readable. When you call print(obj), Python uses __str__. When you use repr(obj) or inspect an object in the REPL, it uses __repr__. If only one is defined, __repr__ serves as the fallback for both.

How does Python handle memory management?

Python uses automatic memory management via reference counting combined with a cyclic garbage collector. Every object tracks how many references point to it; when the count drops to zero the memory is freed immediately. The cyclic GC (gc module) handles reference cycles (e.g., two objects referencing each other). CPython also maintains a free-list for small objects like integers (-5 to 256) and short strings, reusing memory to avoid repeated allocation.