Python Knowledge Flashcards
Stay fresh on Python concepts
How to reverse a string (x) in Python?
x[::-1]
List vs. Tuple
Definition:
Lists are mutable sequences, while tuples are immutable sequences.
- Lists can be changed in-place; tuples cannot.
- Tuples can be used as dictionary keys (hashable), whereas lists cannot.
List Comprehensions
Definition:
A concise syntax for creating lists from iterables with optional conditions.
- Written as:
[expression for item in iterable if some condition]
e.g., Increment item when <9
[item+1 for item in items if item<9]
- Improves readability and can be more efficient than equivalent for-loops.
Generators
Definition:
Functions that use yield to produce a sequence of values lazily.
- Saves memory by not storing the entire sequence in memory.
- Can be iterated over just once (stateful).
GIL (Global Interpreter Lock)
Definition:
A mutex in CPython preventing multiple native threads from executing Python bytecodes simultaneously.
- Affects CPU-bound multi-threading (no true parallelism).
- I/O-bound tasks can still benefit from threading.
Decorator
Definition:
A callable (function or class) that takes another function and extends or modifies its behavior.
- Commonly used for logging, synchronization, caching, or authentication.
- Syntax: @my_decorator above the function definition.
__init__ vs. __new__
Definition:
__init__ initializes an instance after it’s created; __new__ actually creates the instance (rarely overridden).
__init__ is used for most initialization tasks.
__new__ is useful for customizing the creation of immutable types or singletons.
Python Memory Management
Definition:
Uses reference counting and a cyclic garbage collector to free unreachable objects.
- The gc module handles detection and cleanup of reference cycles.
- Reference counting is immediate for zero-count objects.