askesis

Python essentials: 50 core concepts

Learn idiomatic Python fast: comprehensions, f-strings, args and kwargs, generators, decorators, context managers and the standard library.

ProgrammingBeginner50 cardsFree

Practice now

Study without an account

0 of 50 seen0 graduated
Squares of 0–4 with a list comprehension

Scheduled with the default Askesis timings. Progress is saved in this browser.

All 50 cards

  1. 1
    Squares of 0–4 with a list comprehension
    python
    [x * x for x in range(5)]  # [0, 1, 4, 9, 16]
  2. 2
    Dict comprehension
    python
    {word: len(word) for word in words}
  3. 3
    Generator expression
    Like a list comprehension in parentheses, but lazy: values are produced on demand
    python
    total = sum(x * x for x in nums)
  4. 4
    Format a float to 2 decimals with an f-string
    python
    f"{price:.2f}"  # "3.14"
  5. 5
    What does *args collect?
    Extra positional arguments, as a tuple
  6. 6
    What does **kwargs collect?
    Extra keyword arguments, as a dict
  7. 7
    Why is def f(items=[]) a bug?
    The default list is created once and shared between calls; use None and create the list inside
    python
    def f(items=None):
        items = [] if items is None else items
  8. 8
    Reverse a list or string with slicing
    python
    s[::-1]
  9. 9
    What is seq[-1]?
    The last item
  10. 10
    List vs tuple
    Lists are mutable; tuples are immutable (and hashable if their items are)
  11. 11
    is vs ==
    is checks identity (same object); == checks equality
  12. 12
    Falsy values in Python
    None, False, 0, 0.0, '', and empty containers like [], {}, set()
  13. 13
    What does a with block guarantee?
    The context manager’s cleanup runs even if an exception is raised
    python
    with open("notes.txt") as f:
        text = f.read()  # file closed afterwards
  14. 14
    The context manager protocol
    __enter__ and __exit__ methods (or contextlib.contextmanager)
  15. 15
    What is a decorator?
    A function that takes a function and returns a wrapped version, applied with @
    python
    def logged(fn):
        def wrapper(*args, **kwargs):
            print("calling", fn.__name__)
            return fn(*args, **kwargs)
        return wrapper
  16. 16
    Why use functools.wraps?
    It copies the wrapped function’s name, docstring and metadata onto the wrapper
  17. 17
    What does yield do?
    Turns a function into a generator that produces values one at a time, pausing between them
  18. 18
    yield from
    Delegates to another iterable or generator, yielding all its values
  19. 19
    Loop with index and value
    python
    for i, item in enumerate(items, start=1):
        print(i, item)
  20. 20
    What does zip do with uneven lengths?
    Stops at the shortest iterable
    Since Python 3.10, zip(a, b, strict=True) raises instead.
  21. 21
    Read a dict key with a fallback
    python
    d.get("key", default)
  22. 22
    collections.defaultdict
    A dict that creates a default value for missing keys
    python
    groups = defaultdict(list)
    groups[key].append(item)
  23. 23
    collections.Counter
    Counts hashable items
    python
    Counter("banana").most_common(1)  # [('a', 3)]
  24. 24
    sorted(x) vs x.sort()
    sorted returns a new list; .sort() sorts in place and returns None
  25. 25
    Sort words by length
    python
    sorted(words, key=len)
  26. 26
    What is a lambda?
    An anonymous function limited to a single expression
    python
    square = lambda x: x * x
  27. 27
    Extended unpacking
    python
    first, *rest = [1, 2, 3]  # first = 1, rest = [2, 3]
  28. 28
    The walrus operator :=
    Assigns a value inside an expression (Python 3.8+)
    python
    while (line := f.readline()):
        process(line)
  29. 29
    When does the else of a try run?
    Only if no exception was raised in the try block
    finally always runs.
  30. 30
    Raise an exception
    python
    raise ValueError("deck name is empty")
  31. 31
    What is __init__?
    The method that initializes a new instance
  32. 32
    What is self?
    The instance a method is called on, passed explicitly as the first parameter
  33. 33
    @classmethod vs @staticmethod
    A classmethod receives the class (cls); a staticmethod receives neither the class nor the instance
  34. 34
    What does @property do?
    Lets a method be read like an attribute
    python
    class Card:
        @property
        def is_new(self):
            return self.reps == 0
  35. 35
    What does @dataclass generate?
    __init__, __repr__ and __eq__ from the class’s annotated fields
  36. 36
    What is if __name__ == "__main__": for?
    Code under it runs when the file is executed directly, not when it is imported
  37. 37
    Create a virtual environment
    bash
    python -m venv .venv
    source .venv/bin/activate
  38. 38
    The GIL
    In standard CPython, the global interpreter lock lets only one thread run Python bytecode at a time
    Threads still help for I/O-bound work; use processes for CPU-bound work. Python 3.13 adds an optional free-threaded build.
  39. 39
    Is the stop value of range(start, stop) included?
    No, stop is exclusive: range(1, 4) gives 1, 2, 3
  40. 40
    7 // 2 and -7 // 2
    3 and -4: floor division rounds toward negative infinity
  41. 41
    Shallow vs deep copy of a list
    items[:] or list(items) copy one level; copy.deepcopy copies nested objects too
  42. 42
    Join a list of strings
    python
    ", ".join(words)
  43. 43
    Split a string on commas
    python
    "a,b,c".split(",")  # ['a', 'b', 'c']
  44. 44
    Type hints
    python
    def add(a: int, b: int) -> int:
        return a + b
    Hints are not enforced at runtime; tools like mypy check them.
  45. 45
    any and all
    any is true if at least one item is truthy; all is true if every item is (and for an empty iterable)
  46. 46
    What do map and filter return in Python 3?
    Lazy iterators, not lists
  47. 47
    Are dicts ordered?
    Yes. Since Python 3.7, dicts keep insertion order as a language guarantee
  48. 48
    Set operations
    python
    a | b   # union
    a & b   # intersection
    a - b   # difference
  49. 49
    Check if a key is in a dict
    python
    if "key" in d:
        ...
  50. 50
    Unpack a dict into keyword arguments
    python
    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.

Intermediate

JavaScript

Master the JavaScript every developer uses daily: scope, closures, equality, array methods, promises, async/await and the event loop.

50 cards
Intermediate

Advanced 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 cards
Intermediate

TypeScript

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

Git & terminal

The Git commands and shell skills developers use every day: branching, rebasing, undoing mistakes, pipes, redirects, permissions and processes.

50 cards
Beginner

Java

Core Java with short snippets: equals vs ==, records, sealed types, collections, generics, exceptions, streams, lambdas and JVM basics.

50 cards
Beginner

C#

C# and .NET fundamentals with short snippets: value vs reference types, properties, records, nullable reference types, LINQ, async/await and DI.

50 cards
Beginner

Kotlin

Kotlin fundamentals with short snippets: null safety, val vs var, data and sealed classes, extension functions, scope functions and coroutines.

50 cards
Beginner

Swift

Swift fundamentals with short snippets: optionals, structs vs classes, protocols, enums with associated values, closures, ARC, async/await and SwiftUI.

50 cards
Beginner

Flutter

Flutter and Dart basics: null safety, futures and streams, stateless vs stateful widgets, setState, hot reload, keys, layout and state management.

50 cards
Beginner

PHP

Modern PHP 8 with short snippets: strict types, arrays, match, nullsafe and named arguments, enums, readonly, Composer, PDO and password_hash.

50 cards
Beginner

Ruby

Ruby fundamentals with short snippets: blocks, procs and lambdas, symbols, Enumerable, mixins, truthiness, method_missing, gems and Bundler.

50 cards
Beginner

Go

Go (Golang) fundamentals with short, idiomatic snippets: slices vs arrays, maps, defer, error wrapping, interfaces, goroutines, channels, select and context.

50 cards
Intermediate

Rust

Learn the Rust that the compiler keeps asking about: ownership, borrowing, lifetimes, Option and Result, traits, closures, smart pointers and async.

50 cards
Intermediate

C++

Modern C++ in short snippets: references vs pointers, RAII, smart pointers, move semantics, STL containers and algorithms, const, templates and UB.

50 cards
Intermediate

Haskell

Haskell fundamentals with short code: types and type classes, pattern matching, laziness, Maybe and Either, folds, Functor, Applicative and Monad.

50 cards
Intermediate

Elixir

Elixir fundamentals with short snippets: immutability, pattern matching, the pipe operator, Enum vs Stream, processes, GenServer, supervisors and mix.

50 cards
Intermediate

x86-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 cards
Beginner

Regex

Learn regular expressions for good: anchors, classes, greedy vs lazy quantifiers, groups, lookarounds, flags, replacements and the backtracking trap.

50 cards