Neural Sync Active
Week 3: For Loops, Lists, and Tuples
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]2TrueDynamic InjectionCode Generationmy_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:
- Parentheses
(): Highest priority. - Exponents
**: Evaluated next. - Unaries
+x,-x: Positive/Negative signs. - Multiplication
*, Division/, Floor Division//, Modulo%: Evaluated from left to right. - 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): Fromstarttostop - 1.range(start, stop, step): Increment bystep.
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
pythonfruits = ["apple", "banana", "cherry"] print(fruits[1]) # 'banana'
2.2 List Mutability (Changing Elements)
Unlike strings, you can modify elements of a list in-place.
pythonfruits[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) 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).
- Scenario with no index:
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 (→ hash changes → unstable key).
- Tuples: Cannot change (if they contain only immutable items) → stable hash → 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.
pythonfor 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:iis for Index (often used for the outermost loop).jis the next letter in the alphabet, used for the second level.kis used for the third level. You can name themrowandcolfor better clarity in 2D grids! (Useful for handling matrices, 2D grids, or generating combinations).
🧭 Navigation
- 📘 Textbook Notes: Week 3 Notes
- 📝 Assignment: Week 3 Assignment
- ⬅️ Previous Week: Week 2 Notes
- ➡️ Next Week: Week 4 Notes