Iteration Over Arrays - Learn Step by Step
Understanding Iteration in Real Life
Imagine you have a basket of fruits.
You want to:
- Look at each fruit one by one
- Pick only good fruits
- Count how many fruits are good
This is exactly what we do in coding with arrays.
What is Iteration?
Iteration means going through items one by one.
In simple words:
"Take each item and do something with it."
Basic Example
nums = [10, 20, 30]
for x in nums:
print(x)
Explanation:
- First it takes 10
- Then 20
- Then 30
It moves step by step through the list.
When Do We Need Index (Position)?
Sometimes we need to know where the item is.
For example:
- First student
- Second student
nums = [10, 20, 30]
for i in range(len(nums)):
print(i, nums[i])
Explanation:
igives position: 0, 1, 2nums[i]gives value
Output:
0 10
1 20
2 30
Use this when position matters.
Range-based iteration - range_based_iteration
Range-based iteration means: you decide which indices to visit using Python’s range(), then read or update arr[i].
Visit every index
nums = [10, 20, 30]
for i in range(len(nums)):
print(nums[i])
Visit only part of the array
range(start, stop) visits start … stop - 1 ( stop is not included ).
nums = [10, 20, 30, 40, 50]
# indices 1, 2, 3 only
for i in range(1, 4):
print(nums[i])
Skip positions (step)
nums = [1, 2, 3, 4, 5, 6]
# indices 0, 2, 4
for i in range(0, len(nums), 2):
print(nums[i])
Use range(...) when you care about index math, subranges, or steps - not only “every value in order.”
Filtering (Picking Only Needed Values) - conditional_filtering
Imagine:
Pick only good fruits.
Example: pick even numbers
nums = [1, 2, 3, 4, 5]
result = []
for x in nums:
if x % 2 == 0:
result.append(x)
print(result)
Explanation:
- Check each number
- If condition is true, store it
- Otherwise ignore
Output:
[2, 4]
Threshold filtering - threshold_filtering
Threshold filtering means: keep or count values based on a numeric cutoff (a threshold).
Examples of thresholds:
- Pass mark: score
>= 40 - Budget: price
<= 100 - Alert: temperature
> 37.5
scores = [55, 38, 72, 40, 22]
pass_mark = 40
passed = [s for s in scores if s >= pass_mark]
print(passed) # [55, 72, 40]
count = sum(1 for s in scores if s >= pass_mark)
print(count) # 3
Same iteration idea as general filtering - here the condition is usually < / > / <= / >= against one boundary number.
Counting Values - count_tracking
Sometimes we do not store values, we just count.
nums = [5, -2, 3, -1]
count = 0
for x in nums:
if x > 0:
count += 1
print(count)
Explanation:
- Start count at 0
- Increase when condition is true
Output:
2
Timeline processing - timeline_processing
Timeline processing means: your array is ordered along time (hour, day, step index 0, 1, 2, …), and you process it in that order - often with a running total or rule that depends on what happened earlier.
Example: events per day (ordered days)
events_per_day = [0, 2, 1, 0, 3]
running = 0
for day, count in enumerate(events_per_day):
running += count
print(day, "total so far =", running)
Because indices follow time order, one left-to-right loop is enough to simulate “day by day” processing.
Why ordering matters
If the input were not time-ordered, the same loop could mean the wrong thing - so sort first when the problem says “events with timestamps.”
Two-pass algorithm - two_pass_algorithm
Sometimes one scan is not enough because the rule for each element needs a fact about the whole array first.
nums = [10, 20, 30, 40]
# Pass 1 - build a whole-array summary (here: average)
total = 0
for x in nums:
total += x
avg = total / len(nums)
# Pass 2 - use that summary on each element
for x in nums:
if x > avg:
print(x)
Output:
30
40
Passes: O(n) + O(n) = O(n) time, still linear.
Two-pass logic - two_pass_logic
Two-pass logic is the design choice: split the solution into phases so each phase has one clear job.
Typical split:
- Phase A (aggregate): compute something that needs all values (sum, max, frequency table, …)
- Phase B (apply): compare or update each value using the result of phase A
Why do this?
- Correctness: some rules cannot be evaluated per element without global context (like
> average). - Clarity: even when a trickier one-pass exists, two short loops are easier to read and debug.
This is the same pattern as two_pass_algorithm - here we stress separating concerns into multiple phases.
Frequency Array Comparison (Short Intro)
Sometimes we need to check whether two arrays contain the same values with the same counts.
Example:
a = [1, 2, 2, 3]
b = [2, 1, 3, 2]
Both arrays have:
1-> 1 time2-> 2 times3-> 1 time
So they are frequency-equal.
Quick Python way:
from collections import Counter
print(Counter(a) == Counter(b)) # True
Important Note
- One pass →
O(n) - Two passes →
O(n) + O(n) = O(n)(still linear) - seetwo_pass_algorithm/two_pass_logic
Total is still O(n), so it is efficient.
Common Mistakes
- Using index loop when not needed
- Forgetting condition inside loop
- Not initializing count
- Trying to do everything in one loop
Keep the logic simple and clear.
Practice Questions
- Count numbers greater than 10
- Print all odd numbers
- Store numbers divisible by 5
- Count negative numbers
- Print elements at indices 2 to 4 using
range(2, 5) - Filter scores with a pass mark (
threshold_filtering) - Walk a per-day array left to right with a running total (
timeline_processing) - Re-do the average then compare example and name pass 1 vs pass 2 (
two_pass_logic)
Key Points
- Iteration means going one by one
- Loop helps to iterate
range(...)picks which indices to walk (range-based iteration)- Use condition to filter; use thresholds for numeric cutoffs (
threshold_filtering) - Time-ordered data → process in index order (
timeline_processing) - Use count to measure
- Use two passes when you need a global summary first (
two_pass_algorithm,two_pass_logic)
What Next?
Now that you understand iteration,
Next step is learning:
- Sum
- Minimum
- Maximum
Continue here:
/resources/arrays/traversal-patterns
