Registry Synced

Week 3: For Loops, Lists, and Tuples

787 words
4 min read
Course: Jan 2026 - Python Difficulty: Intermediate Setup Focus: Iteration over collections, mutability vs immutability.

Structure Visualizer

Demystifying Python Collections

[
0"Python"
142
2True
]
Dynamic Injection
Code Generation
my_list = ["Python", 42, True]
# Mutability allowed

Operator Precedence (PEMDAS vs BODMAS)
In Python, mathematical expressions follow a strict hierarchy. While you might know it as BODMAS or PEMDAS, the logic is identical:
  1. Parentheses (): Highest priority.
  2. Exponents **: Evaluated next.
  3. Unaries +x, -x: Positive/Negative signs.
  4. Multiplication *, Division /, Floor Division //, Modulo %: Evaluated from left to right.
  5. Addition +, Subtraction -: Lowest priority, evaluated left to right.
Why it matters: 10 + 5 / 5 results in 11.0, not 3.0, because division happens before addition!

1. The for Loop

While a while loop runs based on a condition, a for loop iterates over a sequence (like a string, list, or range). It executes the block of code once for each item in the sequence.
The
f in print(f"...") The f stands for Formatted String Literal (or f-string). It was introduced in Python 3.6 to make string interpolation faster and more readable.
  • How it works: Python looks inside { } curly braces and evaluates the expression within them at runtime.
  • Efficiency: F-strings are faster than % formatting or .format() because they are evaluated as part of the constant folding or more direct bytecode instructions.

1.1 The range() Function

range() is commonly used with for loops to generate a sequence of numbers.
  • range(stop): 0 up to (but not including) stop.
  • range(start, stop): From start to stop - 1.
  • range(start, stop, step): Increment by step.
python
# Prints numbers 0, 1, 2, 3, 4
for i in range(5):
    print(i)

# Prints even numbers: 2, 4, 6, 8
for i in range(2, 10, 2):
    print(i)

1.2 Loop Control: break and continue

  • break: Immediately exits the entire loop.
  • continue: Skips the rest of the current iteration and jumps to the next loop cycle.

2. Lists

A List is an ordered, mutable (changeable) collection of items. Lists can contain mixed data types and are defined using square brackets [].

2.1 Creating and Accessing

python
fruits = ["apple", "banana", "cherry"]
print(fruits[1])  # 'banana'

2.2 List Mutability (Changing Elements)

Unlike strings, you can modify elements of a list in-place.
python
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
Memory Efficiency of Lists
Lists are over-allocated. When you append, Python allocates more space than needed so subsequent appends are O(1)O(1) amortized.

2.3 Common List Methods

  • append(item): Adds an item to the end.
  • insert(index, item): Inserts item at a specific position.
  • remove(item): Removes the first occurrence of the item.
  • pop(index): Removes and returns the item at the index.
    • Scenario with no index: pop() defaults to the last item. This is used when implementing a Stack (Last-In, First-Out).
  • len(list): Returns the number of items.

3. Tuples

A Tuple is similar to a list: it is an ordered collection of items. However, tuples are immutable (they cannot be changed after creation). They use parentheses ().
Why use Tuples as Dictionary Keys?
To be a key in a Python dictionary, an object must be hashable. Hashability requires that the object's hash value never changes during its lifetime.
  • Lists: Can change (\to hash changes \to unstable key).
  • Tuples: Cannot change (if they contain only immutable items) \to stable hash \to valid key.
  • Example: Coordinates (x, y) are often used as keys to map a 2D position to a value.

4. Nested Loops

You can place a loop inside another loop. The inner loop finishes all its iterations for every single iteration of the outer loop.
python
for i in range(3):       # Outer loop (runs 3 times)
    for j in range(2):   # Inner loop (runs 2 times per outer loop)
        print(f"i={i}, j={j}")
What do
i and j mean? These are just variable names. By convention:
  • i is for Index (often used for the outermost loop).
  • j is the next letter in the alphabet, used for the second level.
  • k is used for the third level. You can name them row and col for better clarity in 2D grids! (Useful for handling matrices, 2D grids, or generating combinations).


Document Outline
Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.