For Loops and List Traversal

Definite Iteration

Part of: Algorithms, Iteration & Simulation

When you do know how many times to repeat, once per item in a list, or a fixed number of times, a for loop is cleaner than a while loop. This is definite iteration : the count is known before the loop begins. Looping a fixed number of times range(5) produces the sequence 0,1,2,3,4, five values, starting at 0. The loop variable i automatically becomes each value in turn. No manual update is needed, so for loops cannot accidentally run forever the way while loops can. Traversing a list The most important use of a for loop is the list traversal : visiting every element exactly once: The form for s in scores hands you each element directly. To accumulate a result, you keep a variable (here total) updated on every pass, this pattern is called an accumulator . Counting with a condition Traversal plus a conditional lets you count matching elements: The operator % is the modulo (remainder); v % 2 == 0 is True exactly when v is even. When to use which loop - for : known count or "do this for each element": definite iteration. - while : "repeat until a condition changes": indefinite iteration. When you need positions instead of values, use for i in range(len(nums)) and access nums[i]. Why it

Challenge: Count the Evens