Iterating Through Sequences
Python relies on the for statement to traverse iterable objects efficiently. When processing a collection, the interpreter extracts each item sequentially and assigns it to a temporary loop variable.
developers = ["elena", "marcus", "jin"]
for dev in developers:
print(f"{dev.upper()} has submitted a pull request.")
print("Review cycle complete.")
The loop variable name is arbitrary, but choosing a descriptive singular noun that reflects the collection's contents improves readability. Every indented block following the for header belongs to the loop body and executes once per item. Statements aligned with the for keyword run only after the iteration finishes, making them ideal for summary operations or subsequent workflow steps.
Whitespace and Indentation Mechanics
Unlike languages that use braces or keywords to delimit blocks, Python enforces structure through indentation. Misaligned whitespace triggers runtime or syntax failures. Common pitfalls include:
- Missing indentasion: Forgetting to indent the first line inside a loop raises an
IndentationError. - Inconsistent block alignment: Failing to indent subsequent logical lines breaks the intended control flow.
- Unnecessary indentation: Indenting code that should run independently causes logical errors or syntax violations.
- Trailing indentation: Accidentally indenting post-loop statements forces them in to the iteration cycle.
- Omitted colon: The
forheader must terminate with a colon (:); otherwise, the parser throws aSyntaxError.
Generating and Processing Numeric Data
The built-in range() function produces arithmetic progressions without materializing them in memory immediately. It accepts start, stop, and optional step arguments, where the stop value is exclusive.
for step in range(10, 30, 5):
print(step)
To materialize a sequence, wrap the generator with list():
sequence = list(range(10, 30, 5))
print(sequence) # [10, 15, 20, 25]
Mathematical transformations are straightforward. Python uses the ** operator for exponentiation. You can build a derived collection by appending computed values during iteration:
cubes = []
for num in range(1, 8):
cubes.append(num ** 3)
print(cubes)
For aggregate analysis, Python provides optimized built-ins that operate directly on numeric iterables:
max(collection)retrieves the highest value.min(collection)retrieves the lowest value.sum(collection)calculates the total.
List comprehensions condense iteration, transformation, and accumulation into a single expressive line. The syntax places the expression before the loop clause:
cubes_compact = [n ** 3 for n in range(1, 8)]
print(cubes_compact)
Extracting Subsequences via Slicing
Slicing enables targeted extraction of contiguous segments from a sequence. The syntax follows sequence[start:stop:step], where stop is non-inclusive.
colors = ["red", "green", "blue", "yellow", "purple", "orange"]
print(colors[1:4]) # ['green', 'blue', 'yellow']
print(colors[:3]) # Omits start: begins at index 0
print(colors[-2:]) # Negative index: captures last two items
Slices integrate seamlessly with iteration constructs, allowing you to process only a subset of data:
for shade in colors[2:5]:
print(shade.title())
To duplicate a list entirely, omit both boundaries. This creates a shallow copy rather than a reference alias:
palette_copy = colors[:]
palette_copy.append("cyan")
# Original 'colors' remains unaffected
Working with Immutable Sequences (Tuples)
When data integrity must be guaranteed, Python provides tuples. Defined with parentheses, tuples behave like lists but prohibit item reassignment after instantiation.
dimensions = (800, 600)
print(dimensions[0]) # Access via index works identically to lists
Iteration follows the same pattern as mutable sequences:
for dim in dimensions:
print(f"Resolution axis: {dim}px")
While individual elements cannot be mutated, the variable holding the tuple can be rebound to a new object:
dimensions = (1024, 768) # Valid: reassigns the variable reference
If structural modification is unavoidable, convert the tuple to a list, apply changes, and cast it back:
temp_list = list(dimensions)
temp_list[1] = 900
dimensions = tuple(temp_list)
Slicing operations on tuples return new tuple objects, preserving immutability throughout the extraction process.
Adhering to Python Styling Conventions
Consistent formatting ensures codebases remain maintainable across teams. The official style guide, PEP 8, establishes industry-standard conventions:
- Indentation: Use exactly 4 spaces per nesting level. Avoid mixing tabs and spaces to prevent cross-editor misalignment.
- Line Length: Limit lines to 79 characters for code and 72 for docstrings/comments to accommodate side-by-side viewing and terminal constraints.
- Vertical Spacing: Insert blank lines strategically to separate logical sections, function definitions, and class blocks. Whitespace does not affect execution but drastically improves cognitive parsing.
- Reference: Consult the official specification at
https://peps.python.org/pep-0008/for comprehensive naming conventions, import ordering, and whitespace rules.