Python essentials: 50 core concepts
Learn idiomatic Python fast: comprehensions, f-strings, args and kwargs, generators, decorators, context managers and the standard library.
Practice now
Study without an account
Scheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1Squares of 0–4 with a list comprehensionpython
[x * x for x in range(5)] # [0, 1, 4, 9, 16] - 2Dict comprehensionpython
{word: len(word) for word in words} - 3Generator expressionLike a list comprehension in parentheses, but lazy: values are produced on demandpython
total = sum(x * x for x in nums) - 4Format a float to 2 decimals with an f-stringpython
f"{price:.2f}" # "3.14" - 5What does
*argscollect?Extra positional arguments, as a tuple - 6What does
**kwargscollect?Extra keyword arguments, as a dict - 7Why is
def f(items=[])a bug?The default list is created once and shared between calls; useNoneand create the list insidepythondef f(items=None): items = [] if items is None else items - 8Reverse a list or string with slicingpython
s[::-1] - 9What is
seq[-1]?The last item - 10List vs tupleLists are mutable; tuples are immutable (and hashable if their items are)
- 11
isvs==ischecks identity (same object);==checks equality - 12Falsy values in Python
None,False,0,0.0,'', and empty containers like[],{},set() - 13What does a
withblock guarantee?The context manager’s cleanup runs even if an exception is raisedpythonwith open("notes.txt") as f: text = f.read() # file closed afterwards - 14The context manager protocol
__enter__and__exit__methods (orcontextlib.contextmanager) - 15What is a decorator?A function that takes a function and returns a wrapped version, applied with
@pythondef logged(fn): def wrapper(*args, **kwargs): print("calling", fn.__name__) return fn(*args, **kwargs) return wrapper - 16Why use
functools.wraps?It copies the wrapped function’s name, docstring and metadata onto the wrapper - 17What does
yielddo?Turns a function into a generator that produces values one at a time, pausing between them - 18
yield fromDelegates to another iterable or generator, yielding all its values - 19Loop with index and valuepython
for i, item in enumerate(items, start=1): print(i, item) - 20What does
zipdo with uneven lengths?Stops at the shortest iterableSince Python 3.10,zip(a, b, strict=True)raises instead. - 21Read a dict key with a fallbackpython
d.get("key", default) - 22
collections.defaultdictA dict that creates a default value for missing keyspythongroups = defaultdict(list) groups[key].append(item) - 23
collections.CounterCounts hashable itemspythonCounter("banana").most_common(1) # [('a', 3)] - 24
sorted(x)vsx.sort()sortedreturns a new list;.sort()sorts in place and returnsNone - 25Sort words by lengthpython
sorted(words, key=len) - 26What is a
lambda?An anonymous function limited to a single expressionpythonsquare = lambda x: x * x - 27Extended unpackingpython
first, *rest = [1, 2, 3] # first = 1, rest = [2, 3] - 28The walrus operator
:=Assigns a value inside an expression (Python 3.8+)pythonwhile (line := f.readline()): process(line) - 29When does the
elseof atryrun?Only if no exception was raised in thetryblockfinallyalways runs. - 30Raise an exceptionpython
raise ValueError("deck name is empty") - 31What is
__init__?The method that initializes a new instance - 32What is
self?The instance a method is called on, passed explicitly as the first parameter - 33
@classmethodvs@staticmethodA classmethod receives the class (cls); a staticmethod receives neither the class nor the instance - 34What does
@propertydo?Lets a method be read like an attributepythonclass Card: @property def is_new(self): return self.reps == 0 - 35What does
@dataclassgenerate?__init__,__repr__and__eq__from the class’s annotated fields - 36What is
if __name__ == "__main__":for?Code under it runs when the file is executed directly, not when it is imported - 37Create a virtual environmentbash
python -m venv .venv source .venv/bin/activate - 38The GILIn standard CPython, the global interpreter lock lets only one thread run Python bytecode at a timeThreads still help for I/O-bound work; use processes for CPU-bound work. Python 3.13 adds an optional free-threaded build.
- 39Is the stop value of
range(start, stop)included?No,stopis exclusive:range(1, 4)gives 1, 2, 3 - 40
7 // 2and-7 // 23and-4: floor division rounds toward negative infinity - 41Shallow vs deep copy of a list
items[:]orlist(items)copy one level;copy.deepcopycopies nested objects too - 42Join a list of stringspython
", ".join(words) - 43Split a string on commaspython
"a,b,c".split(",") # ['a', 'b', 'c'] - 44Type hintspython
def add(a: int, b: int) -> int: return a + bHints are not enforced at runtime; tools like mypy check them. - 45
anyandallanyis true if at least one item is truthy;allis true if every item is (and for an empty iterable) - 46What do
mapandfilterreturn in Python 3?Lazy iterators, not lists - 47Are dicts ordered?Yes. Since Python 3.7, dicts keep insertion order as a language guarantee
- 48Set operationspython
a | b # union a & b # intersection a - b # difference - 49Check if a key is in a dictpython
if "key" in d: ... - 50Unpack a dict into keyword argumentspython
connect(**config)
Frequently asked questions
Which Python version does this deck use?
Python 3. Version-specific features, like the walrus operator (3.8) and zip(strict=True) (3.10), are marked.
Is this deck for complete beginners?
It suits anyone who has written a few Python scripts and wants the idioms to become automatic.
Can I add my own code cards?
Yes. Add the deck to your collection; cards support fenced code blocks with syntax highlighting.
More in Programming
JavaScript
Master the JavaScript every developer uses daily: scope, closures, equality, array methods, promises, async/await and the event loop.
50 cardsAdvanced JS
Fifty advanced JavaScript cards: event-loop ordering puzzles, generators and async iteration, this binding, Proxy and Reflect, modules, AbortController and coercion edge cases.
50 cardsTypeScript
Learn the TypeScript you use every day: narrowing, generics, keyof, mapped and conditional types, utility types, satisfies and strict mode, with code on every card.
50 cardsGit & terminal
The Git commands and shell skills developers use every day: branching, rebasing, undoing mistakes, pipes, redirects, permissions and processes.
50 cardsJava
Core Java with short snippets: equals vs ==, records, sealed types, collections, generics, exceptions, streams, lambdas and JVM basics.
50 cardsC#
C# and .NET fundamentals with short snippets: value vs reference types, properties, records, nullable reference types, LINQ, async/await and DI.
50 cardsKotlin
Kotlin fundamentals with short snippets: null safety, val vs var, data and sealed classes, extension functions, scope functions and coroutines.
50 cardsSwift
Swift fundamentals with short snippets: optionals, structs vs classes, protocols, enums with associated values, closures, ARC, async/await and SwiftUI.
50 cardsFlutter
Flutter and Dart basics: null safety, futures and streams, stateless vs stateful widgets, setState, hot reload, keys, layout and state management.
50 cardsPHP
Modern PHP 8 with short snippets: strict types, arrays, match, nullsafe and named arguments, enums, readonly, Composer, PDO and password_hash.
50 cardsRuby
Ruby fundamentals with short snippets: blocks, procs and lambdas, symbols, Enumerable, mixins, truthiness, method_missing, gems and Bundler.
50 cardsGo
Go (Golang) fundamentals with short, idiomatic snippets: slices vs arrays, maps, defer, error wrapping, interfaces, goroutines, channels, select and context.
50 cardsRust
Learn the Rust that the compiler keeps asking about: ownership, borrowing, lifetimes, Option and Result, traits, closures, smart pointers and async.
50 cardsC++
Modern C++ in short snippets: references vs pointers, RAII, smart pointers, move semantics, STL containers and algorithms, const, templates and UB.
50 cardsHaskell
Haskell fundamentals with short code: types and type classes, pattern matching, laziness, Maybe and Either, folds, Functor, Applicative and Monad.
50 cardsElixir
Elixir fundamentals with short snippets: immutability, pattern matching, the pipe operator, Enum vs Stream, processes, GenServer, supervisors and mix.
50 cardsx86-64 assembly
x86-64 assembly in Intel syntax: registers and sub-registers, flags, mov and lea, jumps, the stack frame, the System V calling convention and Linux syscalls.
50 cardsRegex
Learn regular expressions for good: anchors, classes, greedy vs lazy quantifiers, groups, lookarounds, flags, replacements and the backtracking trap.
50 cards