---
tags:
- devops
- l1
- flashcard-deck
- python-automation
---
<!-- wiki:breadcrumb:start -->
[Portal](../../../../library/portal/index.md) | **Level:** [L1: Foundations](../../../../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
python/0dcef0bf87e5	python	easy	python, data-structures, syntax	What is "tuple unpacking"?	Assigning elements of a tuple to multiple variables in one line. \nExample: a, b, c = (1, 2, 3). You can also use \n* for catch-all: first, *rest = (1, 2, 3, \n4) gives rest = [2, 3, 4]. Works with any iterable, not just tuples.	projects/knowledge/interview/python/033-tuple-unpacking.txt
python/0f01d2d70817	python	medium	python, data-structures	What's the difference between a list and a tuple in Python?	A list is mutable (you can change, add, remove elements), while a tuple is immutable (once created, its elements cannot be changed). Tuples are hashable (usable as dict keys), slightly faster, and signal intent that data should not change. Use tuples for fixed collections like coordinates or DB rows.	projects/knowledge/interview/python/003-list-vs-tuple.txt
python/10aa82d3cb09	python	easy	python, syntax	How do you write a comment in Python?	By starting the line with a #. For multi-line explanations, use consecutive # lines. Triple-quoted strings (docstrings) serve a different purpose — they document modules, classes, and functions and are accessible at runtime via __doc__.	projects/knowledge/interview/python/016-python-comments.txt
python/1d5da375cdec	python	easy	python, modules, stdlib	What is the "math" module?	A standard library module providing mathematical functions like sqrt(), ceil(), floor(), log(), and constants like math.pi and math.e. For example, math.sqrt(16) returns 4.0. For more advanced work (arrays, stats), use numpy instead.	projects/knowledge/interview/python/020-math-module.txt
python/22915fe79481	python	easy	python, data-structures	What is a tuple and how does it differ from a list?	An immutable, ordered sequence of items defined with parentheses: t = (1, 2, 3). Because they are immutable, tuples are hashable and can be used as dictionary keys or set elements. A single-element tuple requires a trailing comma: (42,).	projects/knowledge/interview/python/023-what-is-tuple.txt
python/24e3e58de7ae	python	medium	python, functions	What is the difference between return and print?	return sends a value back to the caller and exits the function — it can be captured in a variable or used in expressions. print outputs text to the console for human reading but returns None. A common beginner mistake is using print inside a function and wondering why the result can't be reused.	projects/knowledge/interview/python/012-return-vs-print.txt
python/2a0d341f86d7	python	easy	python, syntax	What is "nested loop"?	A loop placed inside the body of another loop. The inner loop runs completely for each iteration of the outer loop. \nExample: iterating a 2D grid with for row in matrix: for cell in row. Be cautious — deeply nested loops can cause performance issues (O(n^2) or worse).	projects/knowledge/interview/python/036-nested-loop.txt
python/2a8f1c1555c9	python	easy	python, syntax	What are the three logical operators?	and, or, and not. They operate on boolean values and use short-circuit evaluation — and stops at the first False, or stops at the first True. This enables patterns like value = x or default_value to set a fallback when x is falsy.	projects/knowledge/interview/python/018-logical-operators.txt
python/2f31d0839b51	python	hard	python, functions, syntax	What does the yield keyword do?	It turns a function into a generator, allowing it to produce a sequence of values lazily over multiple invocations. Each yield outputs a value and pauses the function; calling next() resumes it. This enables memory-efficient iteration over large datasets since values are generated on demand rather than stored in a list.	projects/knowledge/interview/python/011-what-does-yield-do.txt
python/32595276c0a4	python	easy	python, syntax	What is an "integer division" operator?	// (floor division) divides and returns only the whole number part, discarding the remainder. \nExample: 7 // 2 gives \n3. It always rounds toward negative infinity, so -7 // 2 gives -4 (not -3). Pair with % (modulus) to get both quotient and remainder.	projects/knowledge/interview/python/014-integer-division.txt
python/353b1940b4c9	python	easy	python, functions	What does the input() function always return?	A string value, regardless of what the user types. If you need a number, you must explicitly cast: int(input("Enter a number: ")). Forgetting this cast is one of the most common beginner bugs — comparing input() == 5 will always be False.	projects/knowledge/interview/python/009-input-return-type.txt
python/389c288c084d	python	medium	python, functions, stdlib	What does the open() mode 'a' do?	Opens a file for appending — new writes go to the end without overwriting existing content. If the file does not exist, it is created. Contrast with 'w' which truncates the file. Use 'a' for log files or any case where you want to accumulate data across multiple writes.	projects/knowledge/interview/python/030-file-append-mode.txt
python/3c44b27b66a6	python	hard	python, functions, oop	What is a decorator in Python?	A decorator is a function that takes another function and extends its behavior without modifying it. The @decorator syntax above a function definition wraps it in additional functionality. Common uses: @staticmethod, @property, logging, access control, memoization. Decorators can be stacked and can accept arguments via a decorator factory pattern.	projects/knowledge/interview/python/013-what-is-decorator.txt
python/3ca952837353	python	medium	python, data-structures, syntax	What is a list comprehension in Python?	A concise way to create a new list by iterating over an iterable and optionally filtering. \nExample: [x**2 for x in range(5) if x % 2 == 0] creates [0, 4, 16]. Also supports nested loops and can be turned into generator expressions with parentheses for memory efficiency. Prefer comprehensions over map/filter for readability.	projects/knowledge/interview/python/009-list-comprehension.txt
python/403fa9f717fa	python	easy	python, data-structures	What is a list data type and how is it used?	A mutable, ordered sequence of items defined with square brackets: my_list = [1, 2, 3]. Lists support indexing, slicing, appending, and iteration. They can hold mixed types but in practice usually hold one type. Under the hood, Python lists are dynamic arrays, not linked lists.	projects/knowledge/interview/python/021-what-is-list.txt
python/4237c4f7a3cd	python	easy	python, modules, packaging	How do you install a package in Python?	Using pip: pip install package_name (downloads from PyPI by default). \nBest practice: always install into a virtual environment, not system Python. Use pip install -r requirements.txt for project dependencies, and pin versions for reproducibility (e.g., requests==2.31.0).	projects/knowledge/interview/python/008-install-package.txt
python/43e437b6ff5b	python	hard	python, oop, debugging	What is the purpose of garbage collection in Python?	Python manages memory using reference counting (freeing objects when their refcount hits zero) plus a cyclic garbage collector that detects reference cycles (e.g., two objects pointing at each other). The gc module lets you inspect or force collection. Memory leaks can still happen if objects are unintentionally held in global lists, caches, or closures.	projects/knowledge/interview/python/015-garbage-collection.txt
python/44f94702be08	python	medium	python, modules, syntax	What does if __name__ == "__main__": do?	It checks if the file is being run directly (as a script) vs being imported as a module. Code inside this block only executes on direct run. This idiom lets you put tests, demos, or CLI logic in a module file without it running on import. Every well-structured Python script should use this pattern.	projects/knowledge/interview/python/005-if-name-main.txt
python/47cdf1c0b37f	python	easy	python, syntax	What is Python and what makes it popular for DevOps and scripting?	Python is a high-level, interpreted programming language known for its readable syntax and broad usage in web development, automation, data analysis, AI, and DevOps scripting. Its "batteries included" standard library and large ecosystem (PyPI) make it a go-to language for rapid prototyping and production systems alike.	projects/knowledge/interview/python/001-what-is-python.txt
python/498195d36267	python	medium	python, debugging	What is a "Value Error"?	Raised when a function receives the right type but an inappropriate value. \nExample: int("abc") raises ValueError because "abc" is a string (correct type for int()) but not a valid integer. Handle with try/except ValueError. Common in input parsing, type conversion, and data validation.	projects/knowledge/interview/python/035-value-error.txt
python/4f578c9c04e9	python	easy	python, functions	What function returns the data type of an object?	type(). \nExample: type(42) returns <class 'int'>. For checking whether an object is a specific type, prefer isinstance(obj, int) over type(obj) == int because isinstance also handles subclasses and supports tuple-of-types: isinstance(x, (int, float)).	projects/knowledge/interview/python/007-type-function.txt
python/4fad2cb9e518	python	medium	python, modules, stdlib	What is the "os" module primarily used for?	Interacting with the operating system: file/directory operations (os.listdir, os.remove, os.makedirs), environment variables (os.environ), path manipulation (os.path.join), and process management (os.getpid). For modern path handling, prefer pathlib. For running shell commands, prefer subprocess over os.system.	projects/knowledge/interview/python/040-os-module.txt
python/50e415c81d06	python	easy	python, functions	What does the len() function do?	Returns the number of items in an object — works on strings, lists, tuples, dicts, sets, and any object implementing __len__. \nExample: len("hello") returns 5, len([1,2,3]) returns \n3. Calling len on an object that does not support it raises TypeError.	projects/knowledge/interview/python/013-len-function.txt
python/56087b1e1d58	python	easy	python, syntax	What is "decrementing"?	Subtracting a value (usually one) from a variable, typically in a loop. Python has no -- operator like C/Java; use x -= 1 instead. Incrementing is the opposite: x += 1. These augmented assignment operators also work with other operations: *=, /=, %=.	projects/knowledge/interview/python/039-decrementing.txt
python/562f246765e9	python	medium	python, testing, packaging	What is PEP 8 and why does it matter for Python code?	The official Python style guide promoting consistent, readable code: 4-space indents, snake_case for functions/variables, CamelCase for classes, max 79-char lines. Enforced by linters like ruff, flake8, or pylint. Following PEP 8 is expected in professional Python codebases and code reviews.	projects/knowledge/interview/python/006-what-is-pep8.txt
python/5d1b870f869a	python	medium	python, syntax, debugging	What is the difference between == and is in Python?	== checks value equality (whether two objects have equal values), while is checks identity (whether they are the same object in memory). \nGotcha: small integers (-5 to 256) and short strings are cached/interned by CPython, so is may appear to work but is unreliable for value comparison. Always use == for values; reserve is for None checks (x is None).	projects/knowledge/interview/python/014-equality-vs-identity.txt
python/5ea620b8cce5	python	easy	python, functions	What is the difference between a parameter and an argument?	A parameter is the variable name in a function definition; an argument is the actual value passed when calling the function. \nExample: in def greet(name), name is the parameter; in greet("Alice"), "Alice" is the argument. Python supports positional, keyword, default, and variadic (*args, **kwargs) parameters.	projects/knowledge/interview/python/011-parameter-vs-argument.txt
python/69986a3d9acc	python	medium	python, data-structures, syntax	What is "slicing" in Python?	Accessing a range of items using [start:stop:step] syntax. Works on lists, strings, and tuples. Examples: lst[1:4] gets indices 1-3, lst[::-1] reverses, lst[::2] gets every other element. Slicing returns a new object and never raises IndexError even if indices are out of range — it just returns what is available.	projects/knowledge/interview/python/037-slicing.txt
python/6c31adc4986e	python	easy	python, syntax	What is iteration in programming and what are common patterns?	The repeated execution of a set of statements, typically using a for loop (iterating over a sequence) or a while loop (iterating until a condition is false). Python's for loop works on any iterable: lists, strings, dicts, files, generators. The iter()/next() protocol underlies all iteration.	projects/knowledge/interview/python/027-iteration.txt
python/82fa29313de6	python	easy	python, syntax	Which operator gives the remainder of division?	% (modulus). \nExample: 10 % 3 returns 1. Commonly used to check if a number is even (n % 2 == 0), cycle through indices, or implement wrap-around behavior. In Python, the result always has the same sign as the divisor, unlike some other languages.	projects/knowledge/interview/python/015-modulus-operator.txt
python/8ecebace73a6	python	easy	python, syntax	What is a Boolean data type and how is it used in programming?	A data type representing True or False (capitalized in Python). Booleans are a subclass of int: True == 1, False == 0. Falsy values include 0, None, empty strings, empty collections. Used in conditionals, loops, and logical expressions.	projects/knowledge/interview/python/017-boolean-type.txt
python/9317b6a366cb	python	hard	python, functions	What are *args and **kwargs in Python functions?	*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary. This enables flexible APIs. \nExample: def log(msg, *args, **kwargs) can accept log("error", code, timestamp=now). Order matters in the signature: regular params, *args, keyword-only params, **kwargs. Overusing them hurts readability — prefer explicit parameters when the interface is known.	projects/knowledge/interview/python/004-args-kwargs.txt
python/95747a80b7c2	python	easy	python, modules	What does the `import` statement do in Python?	Loads a module (or specific names from it) into the current namespace so you can use its functions, classes, and variables. Variants: import math (full module), from math import sqrt (single name), from math import \n* (all names — discouraged, pollutes namespace). Python caches imports in sys.modules.	projects/knowledge/interview/python/034-import-statement.txt
python/aacb3404db66	python	medium	python, syntax, debugging	What is "type casting"?	Manually converting a value from one data type to another using built-in constructors: int("42"), float(3), str(100), list("abc"). Also called type conversion. Implicit conversion happens automatically in some cases (int + float yields float). Failed casts raise ValueError or TypeError — always handle these in user-facing code.	projects/knowledge/interview/python/008-type-casting.txt
python/ac5f91d30025	python	medium	python, functions, stdlib	What is the difference between read() and readlines()?	read() returns the entire file as one string; readlines() returns a list where each element is one line. For large files, neither is ideal — iterate line by line with for line in file: instead, which is memory-efficient. readline() reads a single line. Always use context managers (with open(...) as f:) to ensure the file is closed.	projects/knowledge/interview/python/031-read-vs-readlines.txt
python/ad0b4b1690c9	python	easy	python, syntax	Is Python statically or dynamically typed?	Dynamically typed — variable types are determined at runtime and you do not declare types explicitly. You can reassign x = 5 then x = "hello". This adds flexibility but can hide bugs. Type hints (PEP 484) add optional static checking via tools like mypy without changing runtime behavior.	projects/knowledge/interview/python/002-static-vs-dynamic-typing.txt
python/b36979ecbc42	python	easy	python, functions	What value is returned if a function has no return statement?	None. Python implicitly returns None when a function exits without a return statement or with a bare return. This is important when chaining function calls — if you accidentally forget return, downstream code receives None, often causing subtle AttributeError bugs.	projects/knowledge/interview/python/026-no-return-value.txt
python/b79c92ab9734	python	medium	python, debugging	What is an "exception"?	An error raised during execution that disrupts normal program flow. Python has a hierarchy of built-in exceptions (ValueError, TypeError, KeyError, etc.) all inheriting from BaseException. Handle with try/except/finally blocks. You can define custom exceptions by subclassing Exception. Unhandled exceptions produce a traceback and crash the program.	projects/knowledge/interview/python/028-exception.txt
python/c1fe8ee80dcd	python	easy	python, debugging	What is a "Syntax Error"?	An error raised when Python's parser encounters code that violates the language's structural rules — such as missing colons, unmatched brackets, or incorrect indentation. SyntaxErrors are caught before runtime so the program never starts. Read the error message carefully: it points to the line and position of the problem.	projects/knowledge/interview/python/006-syntax-error.txt
python/c60021ecab6a	python	medium	python, data-structures	What is a "dictionary"?	A mutable, unordered (insertion-ordered since Python 3.7) collection of key-value pairs: d = {"name": "Alice", "age": 30}. Keys must be hashable (strings, numbers, tuples). Lookup, insert, and delete are O(1) average. Use .get(key, default) to avoid KeyError. Dicts are the backbone of Python internals — namespaces, kwargs, and JSON all map to dicts.	projects/knowledge/interview/python/024-what-is-dictionary.txt
python/c91fade3b726	python	easy	python, syntax	How does Python define code blocks?	By using indentation (whitespace at the start of a line), not braces like C/Java. The standard is 4 spaces per level (PEP 8). Mixing tabs and spaces causes IndentationError. Consistent indentation is enforced by the parser, making Python code visually structured by default.	projects/knowledge/interview/python/003-code-blocks.txt
python/caa91b57ac6d	python	easy	python, data-structures	How do you add an item to the end of a list?	Using .append(item) to add a single element, or .extend(iterable) to add multiple elements. \nNote: append([1,2]) adds the list as one nested element; extend([1,2]) adds each element individually. For inserting at a specific position, use .insert(index, item).	projects/knowledge/interview/python/022-list-append.txt
python/caf9e931d8ef	python	hard	python, oop, debugging	What is the Global Interpreter Lock (GIL) in Python?	In CPython, the GIL is a mutex allowing only one thread to execute Python bytecode at a time. It simplifies memory management but limits true parallelism for CPU-bound tasks. Workarounds: use multiprocessing for CPU-bound work, or asyncio/threading for I/O-bound work where threads release the GIL during waits. Python 3.13+ experiments with GIL-free builds.	projects/knowledge/interview/python/012-what-is-gil.txt
python/d50f7f4dbfe7	python	medium	python, packaging, modules	What is a virtual environment in Python and why use it?	An isolated Python environment with its own installed packages, avoiding dependency conflicts between projects. Create with python -m venv .venv, activate with source .venv/bin/activate. Each venv has its own site-packages. Essential for reproducible builds — without one, pip install affects the system Python and can break other projects.	projects/knowledge/interview/python/007-virtual-environment.txt
python/db07b3e0f8c3	python	hard	python, functions, data-structures	What is a Python generator?	A generator is a function that uses yield to produce a sequence of values lazily. Each call to next() returns the next value and the function state is preserved between yields. Generators are memory-efficient for large datasets (e.g., reading million-line files). Generator expressions: (x**2 for x in range(10**6)) create generators inline. They are single-use — once exhausted, they cannot be restarted.	projects/knowledge/interview/python/010-what-is-generator.txt
python/e2b32e42c13b	python	easy	python, functions, syntax	What is a "local variable"?	A variable defined inside a function, accessible only within that function's scope. It is created when the function runs and destroyed when it returns. Attempting to access it outside raises NameError. Use the global keyword (sparingly) to modify a module-level variable from within a function.	projects/knowledge/interview/python/025-local-variable.txt
python/e8d27a919177	python	easy	python, syntax	What are variables in Python and how are they defined?	Named references to data stored in memory. In Python, variables do not have fixed types — they are labels pointing to objects. Assignment (x = 42) binds the name x to an integer object. Multiple names can reference the same object. Use descriptive names (user_count, not uc) for readable code.	projects/knowledge/interview/python/004-what-are-variables.txt
python/e9c271291935	python	easy	python, syntax	What is a "high-level" language?	A language abstracted from hardware details, closer to human language than machine code. High-level languages (Python, JavaScript, Ruby) handle memory management and provide rich built-in data structures. \nTrade-off: easier to write and read, but generally slower than low-level languages like C. Python bridges the gap with C extensions and libraries like numpy.	projects/knowledge/interview/python/002-high-level-language.txt
python/ebee927ac8c3	python	easy	python, syntax	How do you check if two values are equal?	Using the == operator, which compares values. \nExample: 5 == 5.0 is True (cross-type equality). For identity comparison (same object in memory), use is. For inequality, use !=. For ordered comparisons: <, >, <=, >=. You can chain comparisons: 1 < x < 10 checks both bounds.	projects/knowledge/interview/python/038-equality-check.txt
python/ecda8dcdce0c	python	easy	python, functions, syntax	What is the "range()" function used for?	Generating a sequence of numbers, typically for loops. range(5) gives 0-4; range(2, \n8) gives 2-7; range(0, 10, \n2) gives even numbers 0-8. It returns a lazy range object (not a list), so range(10**9) uses almost no memory. Convert to a list with list(range(5)) if needed.	projects/knowledge/interview/python/032-range-function.txt
python/f7c1b574c5b2	python	easy	python, syntax	What does case-sensitivity mean in Python?	Uppercase and lowercase letters are treated as distinct — myVar, myvar, and MYVAR are three different names. This applies to variable names, function names, keywords (True not true), and module names. Convention: constants use ALL_CAPS, classes use CamelCase, everything else uses snake_case.	projects/knowledge/interview/python/005-case-sensitivity.txt
python/fa5df96809c2	python	medium	python, functions, stdlib	What does the open() mode 'w' do?	Opens a file for writing and truncates (empties) it immediately — all existing content is lost. If the file does not exist, it is created. This is destructive: accidentally opening a log file with 'w' erases it. Use 'a' to append instead. Always use with open(...) as f: to ensure the file is properly closed.	projects/knowledge/interview/python/029-file-write-mode.txt
python/ff4c204599f9	python	medium	python, debugging, syntax	What is an "infinite loop"?	A loop that never terminates because its exit condition is never met. \nExample: while True: without a break. Common causes: forgetting to increment a counter, wrong comparison operator, or modifying the wrong variable. Ctrl+C sends KeyboardInterrupt to stop it. Sometimes intentional — e.g., event loops and server main loops use while True with break conditions.	projects/knowledge/interview/python/019-infinite-loop.txt

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

## Wiki Navigation

### Next Steps

- Python Algorithms Flashcards *(CLI)* (flashcard_deck, L2)
- Python OOP Flashcards *(CLI)* (flashcard_deck, L2)

### 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 Concepts Flashcards *(CLI)* (flashcard_deck, L0) — 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 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 -->
