11.16 Hands-on Exercises
Tuple Operations Practice combining concatenation, membership, and slicing on a single tuple. >>> t = (10, 20, 30) >>> t = …
Tuple Operations Practice combining concatenation, membership, and slicing on a single tuple. >>> t = (10, 20, 30) >>> t = …
Conceptual Questions What’s the difference between a tuple and a list? Why does (1) not create a tuple, but (1,) does? Why are tuples …
When to Use Tuples The data represents a fixed record (coordinates, RGB values, a database row). The value needs to be a dict key or set …
Single-Element Tuple Forgetting the trailing comma — (1) is an int, not a tuple (see 11.2 Creating Tuples). This silently produces the wrong …
Tuples and File Handling Files store plain text, so “reading a tuple” means parsing each line and explicitly reconstructing the …
Search and aggregate operations on a tuple use the exact same techniques as on a list (see 10.12 Sorting and Searching and 10.14 Common …
flowchart TD A["Memory (3 items)"] --> A1["tuple: 64 bytes"] A --> A2["list: 88 bytes"] B["Literal creation speed"] --> B1["tuple: faster"] …
The general mutable-vs-immutable distinction is covered in 5.9 Mutable vs Immutable Types, and general copying mechanics in 6.5 Copying …
Creating and Accessing >>> nested = ((1, 2, 3), (4, 5, 6)) >>> nested[1][2] 6 Updating Nested Mutable Objects A …
Built-in Functions The same general-purpose sequence functions that work on lists (see 10.8 Built-in Functions) work identically on tuples. …
Tuples have only two methods — a direct consequence of immutability. Every method that would modify a list (append, remove, sort, …; …
+ (Concatenation) Combines two tuples into a new tuple — since tuples are immutable, this can never modify either original. >>> (1, …
flowchart LR P1["1"] --> PK["packing"] P2["2"] --> PK P3["3"] --> PK PK --> PT["point = (1, 2, 3)"] PT --> UP["unpacking"] UP --> U1["x = …
Identical indexing and slicing rules to lists (see 10.3 List Indexing and Slicing) and strings — only the container type, and one copying …
Empty Tuple >>> t = () >>> t () Single-Element Tuple A tuple with exactly one element requires a trailing comma — (1) is …
What Is a Tuple? What Is It? An ordered, immutable collection — like a list, but once created it can never be changed. Written with …
Inventory Manager A small class wrapping a list to manage a collection of items with add/remove/list operations. class InventoryManager: def …
Conceptual Questions What’s the difference between a list and a tuple? Why is list.append() O(1) amortized but list.insert(0, x) O(n)? …
Readable Code Prefer a list comprehension over an equivalent manual for + .append() loop when it stays short and clear — but fall back to a …
Index Errors Accessing an index that doesn’t exist — especially easy off-by-one mistakes near a list’s boundaries. >>> …
Lists and File Handling Lists are the natural in-memory representation of file contents — one element per line or row. Iterating an open …
Reverse def reverse_list(l): return l[::-1] >>> reverse_list([1, 2, 3]) [3, 2, 1] Remove Duplicates (Order-Preserving) …
Time Complexity Operation Complexity Notes l[i] (index) O(1) Direct memory offset l.append(x) O(1) amortized Spare capacity absorbs most …
sort() vs. sorted() sort() sorts a list in place, returning None — use when the original order doesn’t need to be preserved. sorted() …
The general mechanics of assignment, shallow copy, and deep copy are covered in depth in 6.5 Copying Objects — this page focuses on …
flowchart TD M["matrix"] --> R0["row 0: [1, 2, 3]"] M --> R1["row 1: [4, 5, 6]"] M --> R2["row 2: [7, 8, 9]"] matrix[1][2] → 6 — the first …
Traversing for The standard, most Pythonic way to iterate — no manual index bookkeeping needed. >>> for x in [1, 2, 3]: ... …
These are called as len(l), not l.len() — global functions, not methods, the same distinction covered for strings in 9.8 String Functions. …
flowchart TD LM["list methods"] LM --> ADD["Add\nappend, extend, insert"] LM --> REM["Remove\nremove, pop, clear"] LM --> QRY["Query\nindex, …
+ (Concatenation) Concatenates two lists into a brand-new list — neither original list is modified. >>> [1, 2] + [3, 4] [1, 2, 3, …
remove() Removes the first occurrence of a given value (not a position) — raises ValueError if the value isn’t present. >>> l …
All of these mutate the list in place — the list’s identity (id()) stays the same throughout; see 10.11 Copying and Mutability. Update …
Indexing flowchart LR A["10\n0 / -5"] --- B["20\n1 / -4"] --- C["30\n2 / -3"] --- D["40\n3 / -2"] --- E["50\n4 / -1"] Positive indices count …
Empty Lists The starting point for building up a collection incrementally, e.g. inside a loop. >>> items = [] >>> items [] …
What Is a List? What Is It? An ordered, mutable collection that can hold any mix of values, written with square brackets and …
Log Level Analyzer Build a function that scans a batch of log lines and tallies how many fall into each severity level — an at-a-glance …
Conceptual Questions Why are Python strings immutable, and what does that mean for methods like .replace()? What’s the difference …
Assuming a Method Mutates in Place Every string method returns a new string — the original is never changed, since str is immutable (see 9.1 …
Build Large Strings with join(), Not += Accumulating a string with += inside a loop is O(n²); collecting pieces in a list and calling …
Almost everything touched in cloud and infrastructure automation is a string: log lines, Amazon Resource Names (ARNs), IAM policy documents, …
Why Immutability Matters Here Immutability makes strings safe to share across functions, threads, and dict/set keys without defensive …
What Is Regex? A regular expression is a mini-language for describing text patterns — used for validation, extraction, and bulk …
flowchart TD SA["String Algorithms"] SA --> CH["Check\npalindrome, anagram"] SA --> TR["Transform\nreverse, compress"] SA --> …
These are global built-in functions that accept a string as an argument, rather than methods called on the string object itself (len(s) vs. …
Every method below returns a new string (or list/tuple) — none modify the original, consistent with 9.1 Introduction to Strings. Case …
Three Ways to Format flowchart TD A["% operator\nlegacy, printf-style"] --> D["Same output"] B[".format()\nPython 2.7+, readable"] --> D …
Concatenation (+) Joins two strings end-to-end into a new string — the simplest way to build text from pieces, used constantly for messages, …
Indexing and Negative Indexing Every character in a string has a position. Positive indices count from the left starting at 0; negative …
The core escape sequences (\n, \t, \\, quotes) were introduced in 4.13 Escape Characters. This is the complete reference, including the …
Single and Double Quotes Single and double quotes are functionally identical — the choice is purely stylistic, except when the text itself …
flowchart TD S["str"] S --> C["Creation\nquotes, raw, unicode"] S --> I["Indexing & Slicing"] S --> F["Formatting\n% .format f-strings"] S …
User Input Converter Build a function that safely converts input() text to int, float, or bool based on a requested target type, with …
Conceptual Questions What’s the difference between implicit and explicit type conversion? Why does int(3.9) return 3 instead of 4? …
Invalid Conversions Trying to int() a decimal-looking string directly fails, because int() expects a string that’s already a whole …
Choose the Right Data Type Convert to the type that actually matches how the value will be used — don’t leave a numeric value as str …
Five places type conversion shows up constantly in real infrastructure scripts. Environment Variables os.environ always stores values as str …
Every one of these external data sources hands over strings (or, for JSON, occasionally the wrong type) — converting on the way in is a …
Object Creation During Conversion Every conversion call (int(x), str(x), …) creates a brand-new object — it never modifies the …
flowchart TD V["Untrusted value\n(e.g. user input, env var)"] --> T["try:\nint(value)"] T -->|"valid"| S["Success:\nreturn converted value"] …
Three exception types account for nearly every conversion failure — recognizing them immediately tells you what went wrong. ValueError …
Boolean Conversion The truthy/falsy rules themselves are covered from the operator angle in 7.10 Boolean Evaluation — bool() is simply the …
bytes, bytearray, and memoryview themselves are covered in 5.7 Binary Data Types — this section focuses on the conversion rules for …
flowchart TD STR["str"] <--> INT["int"] STR <--> FLOAT["float"] INT <--> FLOAT STR <--> COLL["list / tuple / set"] BOOL["bool"] --> INT BOOL --> FLOAT …
str() Converts virtually any object into its human-readable string representation — used constantly for logging, printing, and building …
The numeric types themselves are covered in 5.3 Numeric Data Types — this section focuses specifically on the rules for converting into each …
Definition What Is It? Manually requesting a conversion by calling the target type as a function — int(x), str(x), float(x), and so on. Why …
flowchart LR subgraph Implicit["Implicit Conversion — Python does it automatically"] I1["int: 1"] --> IR["1 + 2.5 -> 3.5 (float)"] …
flowchart TD TC["Type Conversion"] TC --> IM["Implicit\nPython does it automatically"] TC --> EX["Explicit\nyou call the target type …
CPU Usage Calculator Build a function that takes total CPU time used and elapsed time, and returns the percentage utilization using …
Conceptual Questions What is the difference between == and is? What is short-circuit evaluation, and why does it matter? Explain operator …
Readable Expressions Favor clarity over compactness — an expression that takes an extra half-second to parse mentally, multiplied across …
Operators are the backbone of every monitoring/validation script — these five patterns cover most of what shows up in practice. CPU/Disk …
Efficient Expressions Prefer x in a_set over x in a_list for repeated membership checks on large collections (see 7.7 Membership Operators) …
Using is Instead of == What Goes Wrong? is compares identity, not value — it can appear to work for small integers or short strings, due to …
Several operators behave completely differently depending on the operand type — + means numeric addition for numbers, but concatenation for …
Syntax Python allows writing a < b < c directly, unlike languages where you’d need (a < b) and (b < c) explicitly. …
Syntax What Is It? A one-line if/else that produces a value rather than executing a statement block: value_if_true if condition else …
What Is It? Python treats every value as either “truthy” or “falsy” in a boolean context (if x:, while x:, bool(x)) …
Operator Precedence What Is It? The order in which operators are applied when an expression mixes several of them, without any parentheses …
This section covers is/is not specifically as comparison operators. The underlying concept — a variable being a reference to an object, not …
in What Is It? Tests whether a value exists within a collection (list, string, dict keys, and so on), returning a bool. >>> 3 in …
What Are They? Operators that work on the individual bits of an integer’s binary representation, rather than its decimal value. Why …
flowchart TD subgraph AND["and — True only if BOTH are truthy"] direction LR A1["True and True → True"] A2["True and False → False"] …
What Are They? Operators that compare two values and always return a bool. Why Are They Used? The foundation of every conditional (if, …
= Plain assignment binds a name to a value — already covered in 4.8 Variables and 6.4 Assignment Operations. >>> x = 5 >>> …
The standard mathematical operators, all usable on int and float (and some on other types, see 7.13 Operators with Different Data Types). …
flowchart TD O["Operators"] O --> AR["Arithmetic\n+ - * / // % **"] O --> AS["Assignment\n= += -= ..."] O --> CO["Comparison\n== != < > <= >="] …
Practice Programs Write a function demonstrating UnboundLocalError, then fix it using the global keyword. Given a nested list, show the …
Frequently Asked Questions What is the difference between a variable and an object in Python? Explain the difference between is and == with …
Meaningful Names Choose names that describe what a variable holds (user_count, not uc) — this is the single highest-leverage readability …
UnboundLocalError What Goes Wrong? Referencing a variable inside a function before assigning it, when that same name is also assigned …
DevOps work is full of environment-specific values — variables, in every sense (Python, OS environment, and Terraform), are how …
Passing Variables What Is It? Python passes arguments by “assignment” — the parameter name inside the function becomes a new …
Creation A variable’s lifetime begins the moment it’s first assigned a value. Usage A variable remains usable for as long as its …
flowchart TD B["Built-in\nlen, print, range, ... — always available"] Gs["Global\nnames at module level"] E["Enclosing\nnames in an outer …
Object Reuse Where possible, CPython reuses existing immutable objects instead of allocating new ones for identical values. The two …
Reference Counting What Is It? CPython’s primary memory-management mechanism, introduced in 5.12 Memory Representation — every object …
When shared references aren’t what you want (see 6.2 Objects and Variable References), Python offers three distinct ways to copy a …
Reference Assignment b = a makes b point at the exact same object a does — no data is copied, as covered in 6.2 Objects and Variable …
Stack vs Heap What Is It? The stack holds function call frames — each frame stores its local variable names and the references they point …
Objects, Briefly Every value a variable can refer to — numbers, strings, functions, even classes — is an object with its own identity, type, …
flowchart TD V["Variable"] V --> R["References\nlabel, not a box"] V --> M["Stack vs Heap\nwhere things live"] V --> C["Copying\nshallow vs …
Practice Programs Write a function that takes a list of mixed types and returns counts of how many are int, str, and float. Given a list …
Frequently Asked Questions What is the difference between a list and a tuple? Why is bool considered a subclass of int? What’s the …
Readability Choose the type whose name and behavior best communicate intent — a set clearly signals “uniqueness matters here” in …
Three type-related mistakes that catch even experienced developers off guard occasionally. Unexpected Type Changes Because Python is …
Real infrastructure tooling constantly maps external data (JSON APIs, config files, log lines) into these exact built-in types — …
Picking the right type up front avoids both bugs and performance problems later — three questions to ask for any given piece of data. …
How Python Stores Objects Every Python object lives on the heap and carries metadata beyond its raw value — a reference count and a type …
Implicit Conversion What Is It? Python automatically converts one type to another in certain mixed-type expressions, without you asking — …
type() Returns an object’s exact type. Good for debugging/inspection, but generally NOT recommended for validation logic (see …
Definition What Is It? A MUTABLE object’s value can be changed in place after creation (its id stays the same); an IMMUTABLE …
None Object What Is It? Python’s singleton “no value” object — there is exactly one None in a running program, and its …
These represent raw bytes rather than text — essential whenever Python touches files, network sockets, or any non-text data. bytes An …
set What Is It? A mutable, unordered collection of unique, hashable values. Why Is It Used? Automatic deduplication and fast (O(1) average) …
dict What Is It? Python’s built-in hash map — a mutable, unordered (technically insertion-ordered since 3.7) collection of key-value …
A sequence is an ordered collection accessible by integer index. All four types below share this trait but differ in mutability and typical …
int Whole numbers of arbitrary precision (Python ints don’t overflow like fixed-width integers in C — they grow as large as memory …
Everything Is an Object What Is It? In Python, literally everything — numbers, strings, functions, even classes themselves — is an object …
flowchart TD PDT["Python Data Types"] PDT --> NUM["Numeric\nint / float / complex / bool"] PDT --> SEQ["Sequence\nstr / list / tuple / …
Frequently Asked Syntax Questions What is the difference between a keyword and an identifier? Why does Python use indentation instead of …
A short checklist distilled from every section in this chapter — apply these consistently and most syntax-level code review comments …
Seeing correct syntax structure in realistic scripts reinforces the rules covered across this chapter better than isolated snippets — …
Five error types that account for the vast majority of syntax mistakes, especially for beginners — knowing what each one means makes them …
PEP 8 is Python’s official style guide. This section covers it from the syntax angle — the specific formatting rules that affect how …
Three ways Python’s line-based syntax can be bent — combining lines together, or splitting one statement across several lines. …
A code block is any indented group of statements introduced by a colon-terminated header line. All four kinds below follow the exact same …
Why Every DevOps Engineer Needs Real Linux Fundamentals Docker, Kubernetes, Terraform, and CI/CD runners are not separate from Linux — …
Escape sequences let you embed special or hard-to-type characters inside an ordinary quoted string, using a backslash followed by a code. …
Where Do Linux Logs Live? Two systems coexist on most modern distros: flowchart TB subgraph Sources KERNEL[Kernel Messages] …
print() The standard way to write text to the console. Accepts any number of arguments, converts each to a string, and prints them …
The Storage Stack, Top to Bottom flowchart TB FS["Filesystem: ext4 / xfs"] --> LV["Logical Volume (LVM)"] LV --> VG["Volume Group"] VG --> …
input() What Is It? Pauses the program, displays an optional prompt, and waits for the user to type a line of text and press Enter. Why Is …
What Handles Networking on Linux? Networking is implemented inside the kernel’s network stack; user-space tools (ip, curl, ss) just …
A literal is a value written directly in source code, as opposed to one computed at runtime — 42, "hello", and True are all …
What Is systemd? systemd is the init system and service manager used by most modern Linux distributions (RHEL, Ubuntu, Debian, Amazon Linux …
Concept of Constants What Is It? A value that’s meant to never change after it’s set. Why Doesn’t Python Enforce It? …
What Happens When a Linux Machine Boots? flowchart TD A["1. Firmware: BIOS/UEFI POST"] --> B["2. Bootloader: GRUB2"] B --> C["3. Kernel …
Declaring Variables What Is It? Unlike many languages, Python has no separate declaration step — a variable comes into existence the moment …
What Is a Process? A process is a running instance of a program — it has its own PID (process ID), memory space, open file descriptors, and …
What Are Identifiers? What Is It? Identifiers are the names you give to variables, functions, classes, and modules. What Are the Rules? It …
What Are Linux Permissions? Every file and directory carries three permission sets — for the owner, the group, and others — each with read …
What Are Keywords? What Is It? Reserved words that are part of Python’s own syntax (if, for, def, class, …). The language …
What Are Users and Groups? Every process and file on Linux is owned by a user ID (UID) and a group ID (GID) — numbers, not names. Usernames …
Single-line Comments What Is It? Text starting with # that the interpreter ignores completely, running to the end of the line. Why Is It …
What Are Linux File Types? Linux recognizes seven file types, all visible through the first character of ls -l’s permission string. …
Importance What Is It? In Python, indentation is not just a style preference — it is the syntax that defines block boundaries, replacing the …
What Is a File, Really? On Linux, a filename is just a pointer (a directory entry) to an inode — a data structure holding the file’s …
flowchart LR subgraph Header["Compound statement header"] K["if"] --> I["age"] --> O[">="] --> L["18"] --> C[":"] end Header --> …
What Is the Linux Filesystem? Unlike Windows (C:\, D:\), Linux has one unified tree rooted at /. Every disk, partition, network share, or …
Program Layout What Is It? The conventional top-to-bottom ordering of sections in a Python file. Why Is It Used? A predictable layout means …
You’ve typed commands into a terminal a thousand times. But have you ever stopped to ask what’s actually happening between you …
What Is Syntax? What Is It? Syntax is the set of rules that defines what counts as a validly structured Python statement — where colons go, …
1.1 Writing the Program Choosing an Editor. Any plain-text editor works — VS Code, PyCharm, IDLE, or even Notepad — since a .py file is …
Let’s talk about the kernel — the part of Linux that does all the unglamorous, absolutely essential work while every application on …
What Is Linux Architecture? Linux architecture describes how the system is layered from raw hardware up to the applications you run, and — …
1.1 Installing Python Getting Python onto a machine is the prerequisite for everything else in this guide — the steps differ slightly per OS …
1.1 What Is Python? Definition of Python. Python is a high-level, general-purpose programming language known for readable syntax and a …
If you’re getting into DevOps, cloud, or backend engineering, Linux isn’t optional background knowledge — it’s the ground …
What Is Bash Scripting? Bash (Bourne Again SHell) is both an interactive shell and a scripting language. A Bash script is just a text file …