---
tags:
- devops
- l0
- flashcard-deck
- python-concepts
---
<!-- wiki:breadcrumb:start -->
[Portal](../../../../library/portal/index.md) | **Level:** [L0: Entry](../../../../library/portal/levels.md) | **Topics:** [Python Automation](../../../../library/portal/topics.md) | **Domain:** DevOps & Tooling
<!-- wiki:breadcrumb:end -->

id	category	difficulty	tags	question	answer	source_path
pyconcept/if-elif-else	python-concepts	easy	python, control-flow, keyword	if / elif / else	x = 10\nif x > 20:\n    print("big")\nelif x > 5:\n    print("medium")  # ← this runs\nelse:\n    print("small")\n\nConditions are evaluated top-to-bottom; first True branch wins. elif and else are optional.	concept-reference
pyconcept/for-loop	python-concepts	easy	python, control-flow, keyword	for loop	for name in ["alice", "bob", "carol"]:\n    print(name.upper())\n\nIterates over any iterable: lists, strings, dicts, files, generators, range().	concept-reference
pyconcept/while-loop	python-concepts	easy	python, control-flow, keyword	while loop	n = 5\nwhile n > 0:\n    print(n)\n    n -= 1\n\nRuns as long as the condition is True. Use break to exit early.	concept-reference
pyconcept/break	python-concepts	easy	python, control-flow, keyword	break	for n in range(100):\n    if n > 4:\n        break\n    print(n)  # prints 0 1 2 3 4\n\nExits the innermost loop immediately.	concept-reference
pyconcept/continue	python-concepts	easy	python, control-flow, keyword	continue	for n in range(5):\n    if n == 2:\n        continue\n    print(n)  # prints 0 1 3 4\n\nSkips the rest of the current iteration, jumps to the next one.	concept-reference
pyconcept/pass	python-concepts	easy	python, control-flow, keyword	pass	class NotYet:\n    pass  # placeholder — class body can't be empty\n\ndef todo():\n    pass  # same for functions\n\nDoes nothing. Used as a syntactic placeholder.	concept-reference
pyconcept/def	python-concepts	easy	python, functions, keyword	def (function definition)	def greet(name):\n    return f"hello, {name}"\n\nprint(greet("alice"))  # hello, alice\n\nFunctions are first-class objects — you can pass them, return them, store them.	concept-reference
pyconcept/lambda	python-concepts	easy	python, functions, keyword	lambda (anonymous function)	square = lambda x: x ** 2\nprint(square(5))  # 25\n\nsorted(["bob", "alice"], key=lambda s: len(s))\n# ['bob', 'alice']\n\nSingle-expression functions. No statements, no multi-line.	concept-reference
pyconcept/return	python-concepts	easy	python, functions, keyword	return	def add(a, b):\n    return a + b\n\nresult = add(3, 4)  # 7\n\nSends a value back to the caller and exits the function. Without return, function returns None.	concept-reference
pyconcept/yield	python-concepts	medium	python, functions, keyword	yield (generators)	def countdown(n):\n    while n > 0:\n        yield n\n        n -= 1\n\nfor x in countdown(3):\n    print(x)  # 3 2 1\n\nPauses the function and produces a value. Resumes on next iteration. Memory-efficient for large sequences.	concept-reference
pyconcept/class	python-concepts	easy	python, oop, keyword	class	class Dog:\n    def __init__(self, name):\n        self.name = name\n    def speak(self):\n        return f"{self.name} says woof"\n\nd = Dog("Rex")\nprint(d.speak())  # Rex says woof	concept-reference
pyconcept/self	python-concepts	easy	python, oop, keyword	self	class Counter:\n    def __init__(self):\n        self.count = 0\n    def inc(self):\n        self.count += 1\n\nself is the instance — it's how methods access the object's data. Not a keyword, but always the first parameter.	concept-reference
pyconcept/try-except	python-concepts	easy	python, error-handling, keyword	try / except	try:\n    x = int("not a number")\nexcept ValueError as e:\n    print(f"bad input: {e}")\n\nCatch specific exceptions. Avoid bare except: — always name the exception type.	concept-reference
pyconcept/try-finally	python-concepts	medium	python, error-handling, keyword	try / except / else / finally	try:\n    f = open("data.txt")\nexcept FileNotFoundError:\n    print("missing")\nelse:\n    print(f.read())  # runs only if no exception\nfinally:\n    print("always runs")  # cleanup goes here	concept-reference
pyconcept/raise	python-concepts	easy	python, error-handling, keyword	raise	def divide(a, b):\n    if b == 0:\n        raise ValueError("cannot divide by zero")\n    return a / b\n\nRaise an exception explicitly. raise without args re-raises the current exception in an except block.	concept-reference
pyconcept/assert	python-concepts	easy	python, error-handling, keyword	assert	def avg(nums):\n    assert len(nums) > 0, "empty list"\n    return sum(nums) / len(nums)\n\nRaises AssertionError if condition is False. Disabled with python -O. Use for sanity checks, not input validation.	concept-reference
pyconcept/with	python-concepts	easy	python, keyword, context-manager	with (context manager)	with open("file.txt") as f:\n    data = f.read()\n# f is automatically closed here\n\nGuarantees cleanup (close, unlock, etc.) even if an exception occurs. Calls __enter__ and __exit__ under the hood.	concept-reference
pyconcept/as	python-concepts	easy	python, keyword	as (aliasing)	import numpy as np          # module alias\nwith open("f") as fh:       # bind context manager result\nexcept KeyError as e:        # bind exception to name\n\nas binds a name in import, with, and except statements.	concept-reference
pyconcept/in	python-concepts	easy	python, keyword, operator	in / not in (membership)	print(3 in [1, 2, 3])          # True\nprint("x" not in "hello")      # True\nprint("key" in {"key": 1})     # True (checks keys)\n\nWorks on lists, tuples, sets, dicts (keys), strings (substring).	concept-reference
pyconcept/is	python-concepts	easy	python, keyword, operator	is / is not (identity)	x = None\nif x is None:\n    print("nothing here")\n\na = [1, 2]\nb = a\nprint(a is b)   # True (same object)\nprint(a is [1,2])  # False (different object, same value)\n\nis checks identity (same object in memory). Use == for value equality.	concept-reference
pyconcept/del	python-concepts	easy	python, keyword	del (delete)	x = 42\ndel x         # unbinds the name\n\nlst = [1, 2, 3]\ndel lst[1]    # [1, 3]\n\nd = {"a": 1}\ndel d["a"]    # {}\n\nRemoves a name binding, list element, dict entry, or attribute.	concept-reference
pyconcept/global-nonlocal	python-concepts	medium	python, keyword, scope	global / nonlocal	count = 0\ndef increment():\n    global count\n    count += 1\n\ndef outer():\n    x = 10\n    def inner():\n        nonlocal x\n        x += 1\n    inner()\n    print(x)  # 11\n\nglobal refers to module scope; nonlocal refers to enclosing function scope.	concept-reference
pyconcept/none	python-concepts	easy	python, types	None	def find(lst, target):\n    for item in lst:\n        if item == target:\n            return item\n    return None  # explicit "not found"\n\nresult = find([1,2,3], 99)\nif result is None:\n    print("not found")\n\nPython's null. There is exactly one None object. Always test with is None, not ==.	concept-reference
pyconcept/fstring	python-concepts	easy	python, strings	f-string (formatted string literal)	name = "alice"\nage = 30\nprint(f"{name} is {age} years old")\n\nprint(f"{age:>10}")     # right-align, width 10\nprint(f"{3.14159:.2f}") # 3.14\nprint(f"{1000:,}")      # 1,000\n\nExpressions inside {} are evaluated at runtime. Python 3.6+.	concept-reference
pyconcept/str-methods	python-concepts	easy	python, strings, methods	Common string methods	s = "  Hello, World  "\ns.strip()          # "Hello, World"\ns.lower()          # "  hello, world  "\ns.split(", ")      # ['  Hello', 'World  ']\n"_".join(["a","b"]) # "a_b"\ns.replace("World", "Python")\ns.startswith("  He")  # True\ns.find("World")       # 9 (-1 if not found)\n"42".isdigit()         # True	concept-reference
pyconcept/str-slicing	python-concepts	easy	python, strings	String slicing	s = "python"\ns[0]      # 'p'\ns[-1]     # 'n'\ns[2:4]    # 'th'\ns[:3]     # 'pyt'\ns[3:]     # 'hon'\ns[::-1]   # 'nohtyp' (reverse)\ns[::2]    # 'pto' (every other)\n\nSame [start:stop:step] syntax works on lists and tuples.	concept-reference
pyconcept/list-ops	python-concepts	easy	python, data-structures, list	List operations	a = [3, 1, 2]\na.append(4)        # [3, 1, 2, 4]\na.extend([5, 6])   # [3, 1, 2, 4, 5, 6]\na.insert(0, 99)    # [99, 3, 1, 2, 4, 5, 6]\na.pop()            # returns 6, list shrinks\na.remove(99)       # removes first occurrence\na.sort()           # in-place: [1, 2, 3, 4, 5]\na.reverse()        # in-place: [5, 4, 3, 2, 1]\nlen(a)             # 5	concept-reference
pyconcept/list-comp	python-concepts	easy	python, data-structures, comprehension	List comprehension	squares = [x**2 for x in range(5)]       # [0, 1, 4, 9, 16]\nevens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]\n\nflat = [c for word in ["hi","yo"] for c in word]  # ['h','i','y','o']\n\nMore readable than map/filter for simple transforms.	concept-reference
pyconcept/dict-ops	python-concepts	easy	python, data-structures, dict	Dict operations	d = {"a": 1, "b": 2}\nd["c"] = 3              # add/update\nd.get("z", 0)           # 0 (no KeyError)\nd.pop("b")              # returns 2, removes key\nd.update({"a": 10})     # merge\nd.setdefault("d", 4)    # insert only if missing\n\nfor k, v in d.items():\n    print(k, v)	concept-reference
pyconcept/dict-comp	python-concepts	easy	python, data-structures, comprehension	Dict comprehension	squares = {x: x**2 for x in range(5)}\n# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n\ninverse = {v: k for k, v in squares.items()}\n# {0: 0, 1: 1, 4: 2, 9: 3, 16: 4}	concept-reference
pyconcept/set-ops	python-concepts	easy	python, data-structures, set	Set operations	a = {1, 2, 3}\nb = {2, 3, 4}\n\na | b    # {1, 2, 3, 4}  union\na & b    # {2, 3}        intersection\na - b    # {1}           difference\na ^ b    # {1, 4}        symmetric difference\n\n3 in a   # True (O(1) lookup)\na.add(5)\na.discard(99)  # no error if missing	concept-reference
pyconcept/set-comp	python-concepts	easy	python, data-structures, comprehension	Set comprehension	words = ["hello", "world", "hello"]\nunique_lengths = {len(w) for w in words}  # {5}	concept-reference
pyconcept/tuple-ops	python-concepts	easy	python, data-structures, tuple	Tuple operations	t = (1, "two", 3.0)\nt[0]         # 1\nt[-1]        # 3.0\nlen(t)       # 3\na, b, c = t  # unpacking\n\n# single-element tuple needs trailing comma\none = (42,)\n\n# tuples are immutable — no append, no assignment\n# t[0] = 99  → TypeError	concept-reference
pyconcept/unpacking	python-concepts	medium	python, syntax	Unpacking (* and **)	# Iterable unpacking\nfirst, *rest = [1, 2, 3, 4]  # first=1, rest=[2,3,4]\na, _, b = (1, 2, 3)          # ignore middle value\n\n# Function argument unpacking\ndef f(a, b, c): return a + b + c\nargs = [1, 2, 3]\nf(*args)       # 6\n\nkw = {"a": 1, "b": 2, "c": 3}\nf(**kw)        # 6\n\n# Merge dicts\nmerged = {**d1, **d2}	concept-reference
pyconcept/enumerate	python-concepts	easy	python, builtins	enumerate()	for i, name in enumerate(["alice", "bob", "carol"]):\n    print(f"{i}: {name}")\n# 0: alice\n# 1: bob\n# 2: carol\n\nfor i, ch in enumerate("abc", start=1):\n    print(i, ch)  # 1 a, 2 b, 3 c\n\nReplaces the manual counter pattern. Always prefer over range(len(x)).	concept-reference
pyconcept/zip	python-concepts	easy	python, builtins	zip()	names = ["alice", "bob"]\nages = [30, 25]\n\nfor name, age in zip(names, ages):\n    print(f"{name} is {age}")\n\ndict(zip(names, ages))  # {"alice": 30, "bob": 25}\n\nStops at the shortest iterable. Use itertools.zip_longest to pad.	concept-reference
pyconcept/map-filter	python-concepts	easy	python, builtins	map() and filter()	nums = [1, 2, 3, 4, 5]\n\nlist(map(str, nums))           # ['1','2','3','4','5']\nlist(filter(lambda x: x>3, nums))  # [4, 5]\n\nBoth return lazy iterators. Usually prefer comprehensions:\n[str(n) for n in nums]\n[n for n in nums if n > 3]	concept-reference
pyconcept/any-all	python-concepts	easy	python, builtins	any() and all()	nums = [2, 4, 6, 7, 8]\nany(x > 5 for x in nums)   # True  (at least one)\nall(x > 0 for x in nums)   # True  (every one)\nall(x % 2 == 0 for x in nums)  # False (7 is odd)\n\nShort-circuit: any() stops at first True, all() stops at first False.	concept-reference
pyconcept/sorted	python-concepts	easy	python, builtins	sorted() and .sort()	nums = [3, 1, 2]\nsorted(nums)               # [1, 2, 3] — returns new list\nnums.sort()                # in-place, returns None\n\nwords = ["banana", "apple", "cherry"]\nsorted(words, key=len)             # ['apple', 'banana', 'cherry']\nsorted(words, key=len, reverse=True)  # ['cherry', 'banana', 'apple']\n\nsorted() works on any iterable. .sort() is list-only.	concept-reference
pyconcept/isinstance	python-concepts	easy	python, builtins, types	isinstance() and type()	x = 42\nisinstance(x, int)         # True\nisinstance(x, (int, float))  # True (either type)\ntype(x)                    # <class 'int'>\ntype(x) is int             # True\n\nPrefer isinstance() — it handles subclasses. type() is for exact type checks.	concept-reference
pyconcept/ternary	python-concepts	easy	python, syntax	Conditional expression (ternary)	age = 20\nstatus = "adult" if age >= 18 else "minor"\n\n# In a list\nlabels = ["even" if x % 2 == 0 else "odd" for x in range(5)]\n# ['even', 'odd', 'even', 'odd', 'even']	concept-reference
pyconcept/walrus	python-concepts	medium	python, syntax, operator	Walrus operator (:=)	# Assign and test in one expression\nif (n := len("hello")) > 3:\n    print(f"long: {n} chars")  # long: 5 chars\n\n# In a while loop\nwhile (line := input("> ")) != "quit":\n    print(f"you said: {line}")\n\n# In a comprehension\nresults = [y for x in data if (y := expensive(x)) > threshold]\n\nPython 3.8+. Use sparingly — readability first.	concept-reference
pyconcept/match-case	python-concepts	medium	python, control-flow, keyword	match / case (structural pattern matching)	def handle(command):\n    match command.split():\n        case ["quit"]:\n            return "bye"\n        case ["go", direction]:\n            return f"going {direction}"\n        case ["pick", "up", item]:\n            return f"picked up {item}"\n        case _:\n            return "unknown"\n\nhandle("go north")    # "going north"\nhandle("pick up key") # "picked up key"\n\nPython 3.10+. Matches structure, not just values.	concept-reference
pyconcept/decorator	python-concepts	medium	python, functions	Decorator	def log_calls(fn):\n    def wrapper(*args, **kwargs):\n        print(f"calling {fn.__name__}")\n        return fn(*args, **kwargs)\n    return wrapper\n\n@log_calls\ndef add(a, b):\n    return a + b\n\nadd(1, 2)  # prints "calling add", returns 3\n\n@decorator is syntactic sugar for: add = log_calls(add)	concept-reference
pyconcept/closure	python-concepts	medium	python, functions	Closure	def make_counter(start=0):\n    count = start\n    def increment():\n        nonlocal count\n        count += 1\n        return count\n    return increment\n\nc = make_counter()\nc()  # 1\nc()  # 2\nc()  # 3\n\nThe inner function captures variables from the enclosing scope. They persist after the outer function returns.	concept-reference
pyconcept/args-kwargs	python-concepts	medium	python, functions	*args and **kwargs	def f(*args, **kwargs):\n    print(args)    # tuple of positional args\n    print(kwargs)  # dict of keyword args\n\nf(1, 2, x=3, y=4)\n# (1, 2)\n# {'x': 3, 'y': 4}\n\n# Keyword-only args (after *):\ndef g(a, b, *, verbose=False):\n    pass  # verbose must be passed by name	concept-reference
pyconcept/type-hints	python-concepts	medium	python, types	Type hints	def greet(name: str, times: int = 1) -> str:\n    return (f"hello {name}\\n") * times\n\nfrom typing import Optional\ndef find(lst: list[int], target: int) -> Optional[int]:\n    return target if target in lst else None\n\nHints are not enforced at runtime. Use mypy for static checking. Python 3.9+ allows list[int] instead of List[int].	concept-reference
pyconcept/dataclass	python-concepts	medium	python, oop	dataclass	from dataclasses import dataclass\n\n@dataclass\nclass Point:\n    x: float\n    y: float\n\np = Point(1.0, 2.0)\nprint(p)            # Point(x=1.0, y=2.0)\np == Point(1.0, 2.0)  # True (auto __eq__)\n\nAuto-generates __init__, __repr__, __eq__. Use frozen=True for immutable.	concept-reference
pyconcept/namedtuple	python-concepts	medium	python, data-structures	NamedTuple	from typing import NamedTuple\n\nclass Point(NamedTuple):\n    x: float\n    y: float\n\np = Point(1.0, 2.0)\np.x          # 1.0 (attribute access)\nx, y = p     # unpacking\np[0]         # 1.0 (index access)\n\nImmutable, lightweight, hashable. Great for simple records.	concept-reference
pyconcept/genexpr	python-concepts	medium	python, functions, comprehension	Generator expression	# Parentheses instead of brackets → lazy evaluation\ntotal = sum(x**2 for x in range(1000000))  # no list in memory\n\nlines = (line.strip() for line in open("big.log"))\nfor line in lines:\n    if "ERROR" in line:\n        print(line)	concept-reference
pyconcept/context-mgr-custom	python-concepts	medium	python, context-manager	Custom context manager	from contextlib import contextmanager\n\n@contextmanager\ndef timer():\n    import time\n    start = time.time()\n    yield  # code inside 'with' runs here\n    print(f"elapsed: {time.time() - start:.2f}s")\n\nwith timer():\n    sum(range(10**7))\n# elapsed: 0.23s	concept-reference
pyconcept/property	python-concepts	medium	python, oop	@property	class Circle:\n    def __init__(self, radius):\n        self._radius = radius\n\n    @property\n    def area(self):\n        return 3.14159 * self._radius ** 2\n\nc = Circle(5)\nprint(c.area)  # 78.53975 — no parentheses\n\nMakes a method look like an attribute. Add @area.setter for write access.	concept-reference
pyconcept/staticmethod-classmethod	python-concepts	medium	python, oop	@staticmethod / @classmethod	class Date:\n    def __init__(self, y, m, d):\n        self.y, self.m, self.d = y, m, d\n\n    @classmethod\n    def from_str(cls, s):\n        return cls(*map(int, s.split("-")))\n\n    @staticmethod\n    def is_valid(s):\n        return len(s.split("-")) == 3\n\nDate.from_str("2026-04-11")  # creates Date\nDate.is_valid("2026-04-11")  # True	concept-reference
pyconcept/dunder-init-repr	python-concepts	easy	python, oop	__init__ and __repr__	class Point:\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n    def __repr__(self):\n        return f"Point({self.x}, {self.y})"\n\np = Point(1, 2)\nprint(p)  # Point(1, 2)\n\n__init__ sets up the instance. __repr__ controls how it prints.	concept-reference
pyconcept/dunder-len-getitem	python-concepts	medium	python, oop	__len__ and __getitem__	class Deck:\n    def __init__(self):\n        self.cards = list(range(52))\n    def __len__(self):\n        return len(self.cards)\n    def __getitem__(self, i):\n        return self.cards[i]\n\nd = Deck()\nlen(d)    # 52\nd[0]      # 0\nd[-1]     # 51\nd[2:5]    # [2, 3, 4] — slicing works too	concept-reference
pyconcept/dunder-enter-exit	python-concepts	medium	python, oop, context-manager	__enter__ and __exit__	class TempDir:\n    def __enter__(self):\n        import tempfile\n        self.path = tempfile.mkdtemp()\n        return self.path\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        import shutil\n        shutil.rmtree(self.path)\n        return False  # don't suppress exceptions\n\nwith TempDir() as d:\n    print(d)  # /tmp/xyz — auto-cleaned up after	concept-reference
pyconcept/dunder-add-eq	python-concepts	medium	python, oop	__add__, __eq__, __lt__ (operator overloading)	class Vec:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __add__(self, other):\n        return Vec(self.x + other.x, self.y + other.y)\n    def __eq__(self, other):\n        return self.x == other.x and self.y == other.y\n\nVec(1,2) + Vec(3,4)   # Vec(4, 6)\nVec(1,2) == Vec(1,2)  # True	concept-reference
pyconcept/inheritance	python-concepts	easy	python, oop	Inheritance	class Animal:\n    def speak(self):\n        return "..."\n\nclass Dog(Animal):\n    def speak(self):\n        return "woof"\n\nclass Cat(Animal):\n    def speak(self):\n        return "meow"\n\nfor a in [Dog(), Cat()]:\n    print(a.speak())  # woof, meow\n\nSubclasses override parent methods. Use super() to call the parent.	concept-reference
pyconcept/super	python-concepts	medium	python, oop	super()	class Base:\n    def __init__(self, x):\n        self.x = x\n\nclass Child(Base):\n    def __init__(self, x, y):\n        super().__init__(x)\n        self.y = y\n\nc = Child(1, 2)\nprint(c.x, c.y)  # 1 2\n\nDelegates to the next class in the MRO. Always use super() in __init__ for cooperative inheritance.	concept-reference
pyconcept/async-await	python-concepts	medium	python, async, keyword	async / await	import asyncio\n\nasync def fetch(url):\n    await asyncio.sleep(1)  # simulate I/O\n    return f"data from {url}"\n\nasync def main():\n    results = await asyncio.gather(\n        fetch("a.com"),\n        fetch("b.com"),\n    )\n    print(results)  # both finish in ~1s, not 2s\n\nasyncio.run(main())\n\nFor I/O-bound concurrency. Not parallelism — use multiprocessing for CPU-bound work.	concept-reference
pyconcept/exception-hierarchy	python-concepts	medium	python, error-handling	Exception hierarchy	# Common built-in exceptions:\n# BaseException\n#  ├── KeyboardInterrupt\n#  ├── SystemExit\n#  └── Exception\n#       ├── ValueError\n#       ├── TypeError\n#       ├── KeyError\n#       ├── IndexError\n#       ├── FileNotFoundError\n#       ├── PermissionError\n#       ├── AttributeError\n#       └── RuntimeError\n\n# Custom exceptions:\nclass AppError(Exception):\n    pass\n\nclass NotFoundError(AppError):\n    pass	concept-reference
pyconcept/custom-exception	python-concepts	medium	python, error-handling	Custom exceptions	class ValidationError(Exception):\n    def __init__(self, field, message):\n        self.field = field\n        super().__init__(f"{field}: {message}")\n\ntry:\n    raise ValidationError("email", "invalid format")\nexcept ValidationError as e:\n    print(e)        # email: invalid format\n    print(e.field)  # email	concept-reference
pyconcept/comprehension-nested	python-concepts	medium	python, comprehension	Nested comprehension	matrix = [[1,2,3], [4,5,6], [7,8,9]]\n\n# Flatten\nflat = [x for row in matrix for x in row]\n# [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# Transpose\ntranspose = [[row[i] for row in matrix] for i in range(3)]\n# [[1,4,7], [2,5,8], [3,6,9]]	concept-reference
pyconcept/defaultdict	python-concepts	easy	python, data-structures, collections	collections.defaultdict	from collections import defaultdict\n\ncounts = defaultdict(int)\nfor word in "the cat sat on the mat".split():\n    counts[word] += 1\n# {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}\n\ngroups = defaultdict(list)\nfor name, dept in [("alice","eng"), ("bob","eng"), ("carol","hr")]:\n    groups[dept].append(name)\n# {'eng': ['alice','bob'], 'hr': ['carol']}	concept-reference
pyconcept/counter	python-concepts	easy	python, data-structures, collections	collections.Counter	from collections import Counter\n\nc = Counter("mississippi")\n# Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1})\nc.most_common(2)  # [('s', 4), ('i', 4)]\n\nwords = "the cat sat on the mat".split()\nCounter(words)  # Counter({'the': 2, 'cat': 1, ...})	concept-reference
pyconcept/deque	python-concepts	medium	python, data-structures, collections	collections.deque	from collections import deque\n\nq = deque([1, 2, 3])\nq.append(4)      # right: [1, 2, 3, 4]\nq.appendleft(0)  # left:  [0, 1, 2, 3, 4]\nq.pop()           # 4\nq.popleft()       # 0\n\n# Fixed-size buffer (keeps last N)\nbuf = deque(maxlen=3)\nfor i in range(5):\n    buf.append(i)\nprint(buf)  # deque([2, 3, 4])	concept-reference
pyconcept/itertools	python-concepts	medium	python, stdlib, itertools	itertools essentials	import itertools\n\n# chain — flatten iterables\nlist(itertools.chain([1,2], [3,4]))  # [1, 2, 3, 4]\n\n# islice — lazy head/tail\nlist(itertools.islice(range(100), 5))  # [0, 1, 2, 3, 4]\n\n# groupby (must be sorted first)\nfrom itertools import groupby\ndata = sorted(["aa", "ab", "ba", "bb"], key=lambda x: x[0])\nfor k, g in groupby(data, key=lambda x: x[0]):\n    print(k, list(g))  # a ['aa','ab'], b ['ba','bb']\n\n# product — nested loops\nlist(itertools.product("AB", "12"))  # [('A','1'),('A','2'),('B','1'),('B','2')]	concept-reference
pyconcept/functools	python-concepts	medium	python, stdlib, functools	functools essentials	from functools import lru_cache, partial, reduce\n\n# lru_cache — memoization\n@lru_cache(maxsize=128)\ndef fib(n):\n    return n if n < 2 else fib(n-1) + fib(n-2)\nfib(100)  # instant\n\n# partial — fix some arguments\nfrom functools import partial\nint_from_hex = partial(int, base=16)\nint_from_hex("ff")  # 255\n\n# reduce — fold a sequence\nreduce(lambda a, b: a * b, [1,2,3,4])  # 24	concept-reference
pyconcept/pathlib	python-concepts	easy	python, stdlib, filesystem	pathlib basics	from pathlib import Path\n\np = Path("/var/log/syslog")\np.name       # "syslog"\np.parent     # Path("/var/log")\np.suffix     # "" (no extension)\np.exists()   # True/False\np.read_text()  # file contents as string\n\n# Build paths with /\nconf = Path.home() / ".config" / "myapp"\nconf.mkdir(parents=True, exist_ok=True)\n\n# Glob\nfor f in Path("/var/log").glob("*.log"):\n    print(f)	concept-reference
pyconcept/subprocess-basic	python-concepts	easy	python, stdlib, subprocess	subprocess basics	import subprocess\n\n# Run a command, capture output\nresult = subprocess.run(\n    ["ls", "-la"],\n    capture_output=True, text=True, check=True,\n)\nprint(result.stdout)\n\n# NEVER use shell=True with user input\n# Always pass args as a list	concept-reference
pyconcept/re-basics	python-concepts	medium	python, stdlib, regex	re (regular expressions)	import re\n\n# Search\nm = re.search(r"(\\d+)", "error on line 42")\nm.group(1)  # "42"\n\n# Find all\nre.findall(r"\\b\\w+@\\w+\\.\\w+\\b", text)\n\n# Sub (replace)\nre.sub(r"\\s+", " ", "too   many   spaces")  # "too many spaces"\n\n# Split\nre.split(r"[;,]\\s*", "a, b; c")  # ['a', 'b', 'c']\n\n# Compile for reuse\npattern = re.compile(r"ERROR: (.+)")	concept-reference
pyconcept/json-yaml	python-concepts	easy	python, stdlib, serialization	JSON and YAML	import json\n\n# JSON\ndata = {"name": "alice", "age": 30}\njson.dumps(data)               # string\njson.dumps(data, indent=2)     # pretty\njson.loads('{"x": 1}')         # dict\n\nwith open("f.json") as f:\n    data = json.load(f)         # from file\n\n# YAML (pip install pyyaml)\nimport yaml\nyaml.safe_load(open("f.yaml"))\nyaml.dump(data, default_flow_style=False)	concept-reference
pyconcept/datetime	python-concepts	easy	python, stdlib	datetime	from datetime import datetime, timedelta\n\nnow = datetime.now()\nprint(now.strftime("%Y-%m-%d %H:%M:%S"))\n\ndt = datetime.strptime("2026-04-11", "%Y-%m-%d")\n\ntomorrow = now + timedelta(days=1)\ndelta = datetime(2026, 12, 31) - now\nprint(f"{delta.days} days left")	concept-reference
pyconcept/logging	python-concepts	medium	python, stdlib	logging	import logging\n\nlogging.basicConfig(\n    level=logging.INFO,\n    format="%(asctime)s %(levelname)s %(message)s",\n)\nlog = logging.getLogger(__name__)\n\nlog.debug("details")    # hidden (below INFO)\nlog.info("started")     # shown\nlog.warning("slow")     # shown\nlog.error("failed")     # shown\n\nUse logging, not print(), in production code.	concept-reference
pyconcept/argparse	python-concepts	medium	python, stdlib, cli	argparse	import argparse\n\np = argparse.ArgumentParser(description="greet user")\np.add_argument("name")\np.add_argument("-n", "--count", type=int, default=1)\np.add_argument("-v", "--verbose", action="store_true")\nargs = p.parse_args()\n\nfor _ in range(args.count):\n    print(f"hello {args.name}")\n\n# Usage: python greet.py alice -n 3 -v	concept-reference
pyconcept/threading	python-concepts	medium	python, concurrency	threading	from concurrent.futures import ThreadPoolExecutor\nimport urllib.request\n\ndef fetch(url):\n    return urllib.request.urlopen(url).read()[:100]\n\nurls = ["https://example.com"] * 5\nwith ThreadPoolExecutor(max_workers=5) as pool:\n    results = list(pool.map(fetch, urls))\n\nGood for I/O-bound tasks. GIL prevents true CPU parallelism — use ProcessPoolExecutor for that.	concept-reference
pyconcept/multiprocessing	python-concepts	medium	python, concurrency	multiprocessing	from concurrent.futures import ProcessPoolExecutor\n\ndef crunch(n):\n    return sum(i*i for i in range(n))\n\nwith ProcessPoolExecutor(max_workers=4) as pool:\n    results = list(pool.map(crunch, [10**6]*4))\n\nBypasses the GIL — true parallelism for CPU-bound work. Each worker is a separate process.	concept-reference
pyconcept/slots	python-concepts	hard	python, oop, performance	__slots__	class Point:\n    __slots__ = ("x", "y")\n    def __init__(self, x, y):\n        self.x = x\n        self.y = y\n\np = Point(1, 2)\n# p.z = 3  → AttributeError (no dynamic attrs)\n\n~40% less memory per instance. Use when creating millions of objects.	concept-reference
pyconcept/abc	python-concepts	medium	python, oop	Abstract base class (ABC)	from abc import ABC, abstractmethod\n\nclass Shape(ABC):\n    @abstractmethod\n    def area(self) -> float:\n        ...\n\nclass Circle(Shape):\n    def __init__(self, r):\n        self.r = r\n    def area(self):\n        return 3.14 * self.r ** 2\n\n# Shape()   → TypeError (can't instantiate)\nCircle(5).area()  # 78.5	concept-reference
pyconcept/protocol	python-concepts	hard	python, types	Protocol (structural typing)	from typing import Protocol\n\nclass Closable(Protocol):\n    def close(self) -> None: ...\n\ndef shutdown(obj: Closable) -> None:\n    obj.close()\n\n# Any object with a .close() method works\n# No inheritance needed — duck typing + type checking\nshutdown(open("/dev/null"))  # file has .close()	concept-reference
pyconcept/string-bytes	python-concepts	medium	python, types	str vs bytes	s = "hello"           # str (unicode text)\nb = b"hello"           # bytes (raw bytes)\n\n# Encode: str → bytes\nb = s.encode("utf-8")  # b'hello'\n\n# Decode: bytes → str\ns = b.decode("utf-8")  # 'hello'\n\n# You WILL hit this at network/file boundaries\n# Always decode bytes to str as early as possible	concept-reference
pyconcept/os-environ	python-concepts	easy	python, stdlib, os	os.environ	import os\n\nhome = os.environ["HOME"]               # raises KeyError if missing\ndb = os.environ.get("DB_HOST", "localhost")  # default if missing\nos.environ["MY_VAR"] = "value"           # set for this process\n\n# List all env vars starting with AWS_\naws = {k: v for k, v in os.environ.items() if k.startswith("AWS_")}	concept-reference
pyconcept/shutil	python-concepts	easy	python, stdlib, filesystem	shutil	import shutil\n\nshutil.copy2("a.txt", "b.txt")      # cp -p (preserves metadata)\nshutil.copytree("src/", "dst/")     # cp -r\nshutil.move("old.txt", "new.txt")   # mv\nshutil.rmtree("/tmp/build")         # rm -rf\nshutil.which("python3")             # /usr/bin/python3\n\nusage = shutil.disk_usage("/")\nprint(f"{usage.free // 1e9:.0f} GB free")	concept-reference
pyconcept/tempfile	python-concepts	easy	python, stdlib, filesystem	tempfile	import tempfile\n\n# Temp file (auto-deleted)\nwith tempfile.NamedTemporaryFile(mode="w", suffix=".txt") as f:\n    f.write("data")\n    print(f.name)  # /tmp/tmpXXXX.txt\n\n# Temp directory (auto-deleted)\nwith tempfile.TemporaryDirectory() as d:\n    print(d)  # /tmp/tmpXXXXXX	concept-reference
pyconcept/secrets	python-concepts	easy	python, stdlib, security	secrets (secure random)	import secrets\n\n# Secure token\ntok = secrets.token_hex(16)    # "a3f2...d1b7" (32 hex chars)\ntok = secrets.token_urlsafe(16)  # URL-safe base64\n\n# Secure random integer\nn = secrets.randbelow(100)     # 0-99\n\n# Secure password\nimport string\nalpha = string.ascii_letters + string.digits\npwd = "".join(secrets.choice(alpha) for _ in range(16))\n\nUse secrets, not random, for anything security-related.	concept-reference
pyconcept/hashlib	python-concepts	easy	python, stdlib, security	hashlib	import hashlib\n\nh = hashlib.sha256(b"hello world").hexdigest()\n# "b94d27b9934d3e08a52e52d7da7dabfa..."\n\n# Hash a file\ndef file_hash(path):\n    h = hashlib.sha256()\n    with open(path, "rb") as f:\n        for chunk in iter(lambda: f.read(8192), b""):\n            h.update(chunk)\n    return h.hexdigest()	concept-reference
pyconcept/for-else	python-concepts	medium	python, control-flow	for/else and while/else	for n in [2, 3, 5, 7]:\n    if n == 4:\n        print("found 4")\n        break\nelse:\n    print("4 not found")  # ← runs because no break\n\nThe else block runs only if the loop completes without break. Useful for search patterns.	concept-reference
pyconcept/assignment-expr	python-concepts	easy	python, syntax	Augmented assignment	x = 10\nx += 5   # 15\nx -= 3   # 12\nx *= 2   # 24\nx //= 5  # 4\nx **= 3  # 64\nx %= 10  # 4\n\nAlso works with strings: s = "hi"; s += "!" → "hi!"	concept-reference
pyconcept/truthiness	python-concepts	easy	python, types	Truthy and falsy values	# Falsy values:\nbool(0)       # False\nbool(0.0)     # False\nbool("")      # False\nbool([])      # False\nbool({})      # False\nbool(None)    # False\nbool(False)   # False\n\n# Everything else is truthy:\nbool(1)       # True\nbool("hi")    # True\nbool([0])     # True (non-empty list)\n\n# So you can write:\nif my_list:  # instead of if len(my_list) > 0	concept-reference
pyconcept/scope-legb	python-concepts	medium	python, scope	LEGB scope rule	x = "global"\n\ndef outer():\n    x = "enclosing"\n    def inner():\n        x = "local"\n        print(x)  # local\n    inner()\n    print(x)      # enclosing\n\nouter()\nprint(x)          # global\n\n# Python searches: Local → Enclosing → Global → Built-in\n# import builtins to see the B layer	concept-reference
pyconcept/string-multiline	python-concepts	easy	python, strings	Multi-line strings and docstrings	# Triple quotes for multi-line\nquery = """\nSELECT *\nFROM users\nWHERE active = true\n"""\n\n# Docstrings\ndef add(a, b):\n    """Return the sum of a and b."""\n    return a + b\n\nprint(add.__doc__)  # "Return the sum of a and b."	concept-reference
pyconcept/frozen-set	python-concepts	easy	python, data-structures	frozenset	a = frozenset([1, 2, 3])\n# a.add(4)  → AttributeError (immutable)\n\n# Can use as dict key or set element\ncache = {frozenset([1,2]): "result"}\n\n# Same set operations work\na | frozenset([3, 4])  # frozenset({1, 2, 3, 4})	concept-reference
pyconcept/zip-dict	python-concepts	easy	python, builtins	zip tricks	# Transpose a matrix\nmatrix = [(1,2,3), (4,5,6)]\nlist(zip(*matrix))  # [(1,4), (2,5), (3,6)]\n\n# Unzip\npairs = [("a",1), ("b",2), ("c",3)]\nkeys, vals = zip(*pairs)\n# keys = ('a','b','c'), vals = (1,2,3)	concept-reference
pyconcept/classvar-vs-instancevar	python-concepts	medium	python, oop	Class variable vs instance variable	class Dog:\n    species = "canine"  # class variable (shared)\n\n    def __init__(self, name):\n        self.name = name  # instance variable (per-object)\n\na = Dog("rex")\nb = Dog("fido")\nDog.species    # "canine"\na.name         # "rex"\n\n# Gotcha: mutable class vars are shared!\nclass Bad:\n    items = []  # all instances share this list	concept-reference

<!-- wiki:related:start -->
---

## Wiki Navigation

### Related Content

- Perl Flashcards *(CLI)* (flashcard_deck, L1) — Python Automation
- Python Algorithms Flashcards *(CLI)* (flashcard_deck, L2) — Python Automation
- [Python Async & Concurrency](../../../../library/topics/python-async-concurrency/index.md) (Topic Pack, L2) — Python Automation
- [Python Debugging](../../../../library/topics/python-debugging/index.md) (Topic Pack, L1) — Python Automation
- [Python Drills](../../../../library/drills/python_drills.md) (Drill, L0) — Python Automation
- Python Exercises (Quest Ladder) *(CLI)* (Exercise Set, L0) — Python Automation
- Python Flashcards *(CLI)* (flashcard_deck, L1) — Python Automation
- Python OOP Flashcards *(CLI)* (flashcard_deck, L2) — Python Automation
- [Python Packaging](../../../../library/topics/python-packaging/index.md) (Topic Pack, L2) — Python Automation
- [Python for Infrastructure](../../../../library/topics/python-infra/index.md) (Topic Pack, L1) — Python Automation

<!-- wiki:related:end -->
