Loops
Programming
Algorithms
Coding Techniques
Software Development

Alternate between operations in a for-loop

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Alternating behavior inside a loop is a common requirement: add then subtract, call API A then B, or apply two different transforms in turn. Many implementations start with manual flags that become hard to read when conditions grow. A cleaner approach is to choose an explicit alternation strategy based on your use case: index parity, iterator cycling, or state-machine style toggling. The goal is not just to make the loop work, but to keep intent obvious under maintenance. This article shows reliable patterns in Python and explains when each pattern is better for correctness, extensibility, and performance.

Core Sections

1. Index parity for simple two-way alternation

If your operation depends only on even/odd position, parity is the clearest option.

python
1values = [10, 5, 8, 3, 9]
2result = 0
3
4for i, v in enumerate(values):
5    if i % 2 == 0:
6        result += v
7    else:
8        result -= v
9
10print(result)

This approach is deterministic and easy to test. It is ideal when skipping elements is not part of the logic.

2. Cycle through operation functions

When alternation may expand beyond two operations, use itertools.cycle.

python
1from itertools import cycle
2
3def add(acc, x):
4    return acc + x
5
6def mul(acc, x):
7    return acc * x
8
9ops = cycle([add, mul])
10acc = 1
11for x in [2, 3, 4, 5]:
12    acc = next(ops)(acc, x)
13
14print(acc)

This decouples operation selection from loop structure and scales cleanly to 3+ phases.

3. Toggle state when alternation depends on runtime events

If you need to skip alternation on certain elements, explicit state is better than parity.

python
1toggle = True
2result = []
3
4for token in ["A", "skip", "B", "C", "skip", "D"]:
5    if token == "skip":
6        continue
7
8    if toggle:
9        result.append(token.lower())
10    else:
11        result.append(token.upper())
12
13    toggle = not toggle
14
15print(result)

Here, alternation only advances when meaningful work occurs.

4. Encapsulate alternating logic

For reuse, wrap alternation in a helper that accepts operations and data. This prevents duplicated parity checks across code paths.

python
1from typing import Callable, Iterable, TypeVar, List
2
3T = TypeVar("T")
4
5def alternate_apply(items: Iterable[T], f1: Callable[[T], T], f2: Callable[[T], T]) -> List[T]:
6    out = []
7    for i, item in enumerate(items):
8        out.append(f1(item) if i % 2 == 0 else f2(item))
9    return out

When code reads like a domain operation rather than a loop trick, maintenance improves significantly.

5. Testing alternating behavior

Alternation bugs are often off-by-one issues. Add tests for empty input, single element, odd length, even length, and skipped-element scenarios. These small tests catch most regressions immediately.

Validation and production readiness

A reliable implementation should include more than a working snippet. Add a small reproducible dataset or input fixture that exercises expected behavior and edge cases, then codify it in automated tests. Include at least one “happy path,” one malformed input case, and one boundary condition so regressions are caught early. Instrument key steps with structured logs or metrics to make failures diagnosable in runtime environments, not just local development. If performance is relevant, keep a lightweight benchmark that can be rerun after refactors to ensure behavior stays within budget.

Operationally, document assumptions near the code: required library versions, environment variables, timezone/locale expectations, and failure handling strategy. For team workflows, add one integration test that mirrors real usage rather than only unit-level checks. This reduces drift between example code and production behavior. Treat these checks as part of feature completion, because most long-term issues are caused by unvalidated assumptions rather than syntax errors.

Common Pitfalls

  • Hiding alternation in complex inline expressions that obscure intent.
  • Using index parity when loop control (continue) changes alternation semantics.
  • Forgetting whether alternation should reset between batches of input.
  • Extending two-operation logic ad hoc instead of switching to a cycle-based design.
  • Missing boundary tests that expose off-by-one behavior on short lists.

Summary

Alternating operations in a loop is simple when you choose the right pattern. Use parity for strict position-based behavior, cycle for extensible operation sequences, and explicit state when alternation depends on runtime conditions. Keep logic encapsulated and test boundaries aggressively. With these practices, alternating loops stay readable, correct, and easy to evolve.


Course illustration
Course illustration

All Rights Reserved.