List iteration

Learn this with friends

ComputingIntro to computer science - Python4:545 check-ins

About this video

To operate on every element of a list, we use loops. The video moves from a while loop over indices, to a for loop with range(len(list)), to a for-each loop that iterates by element. Iterating by element is shortest, but it copies each value into the loop variable, so to modify the list or use the indices you must iterate by index.

You'll be able to

  • write a loop that iterates over a list by index using range(len(list)).
  • write a for-each loop that iterates over a list by element.
  • explain why a for-each loop can't modify the elements of the list.
  • choose between iterating by index and by element.

Key words

iterate
To go through each item in a collection, one at a time.
iterating by index
Looping over the positions 0 to len - 1 and using each index to access the list.
for-each loop
A loop like 'for grade in scores:' that gives you each element directly.
loop variable
The variable that takes a new value on each iteration of the loop.
range
A function that produces numbers from a start (0 by default) up to, but not including, a stop value.
Transcript

- [Speaker] You have a list of related data, but now what? Well, in most cases, you want to operate on every element in the list, whether that's searching for particular values or modifying every element. Let's start by doing this the hard way. Say I have a list of test scores and I want to count how many are above or equal to 90.

Well, certainly, I can access the test at every index individually and do that comparison. But I'm repeating myself a lot. And if I add more test scores, then I'll have to go in and add another one of these checks. This problem kind of looks familiar. How do we solve it before?

We used loops! Alright, so let's apply what we know about loops to iterate over the elements of my list. We want to go through every possible list index and access the element there. Indices start at zero, so let's initialize our loop variable to zero. And on each iteration, we'll increment the index by one.

A quick reminder on our plus equals syntax shortcut for self-referencing assignment statements. This is equivalent to index equals index plus one. Okay, but when do we stop? Well, when we get to the end of the list, we know that the last element of a list is at the index length of the list, minus one.

So that should be our last iteration, which means we want to stop when index equals the length of the list. Then, we just move that conditional inside the loop body, so we do that comparison on every iteration. And since I generalized my loop to stop based on the length of the list and not a hardcoded value, like four, my calculations still work no matter how many tests I have in my list.

Now, if you're like, "Hey, why you making me use while loops?", you're absolutely right. We typically do list iteration using for loops because it's less code. You may have wondered before why range starts at zero by default and why its stop value is exclusive.

It's because it was invented for this exact situation: lists! Instead of putting a hardcoded value as the stop argument to the range function, we can pass it the length of the list. So, it'll start at zero and it'll stop when the loop variable index reaches the length of the list.

Wow! By convention, we shorten the loop variable name to i. if it represents the index of a list. We move that conditional inside the loop body, and once again, we have an equivalent program, but with even less code. But can we go deeper? Programming language developers recognized that programmers will very frequently want to iterate over the elements of a list.

So, many of them invented a syntax shortcut called a for-each loop. That is: for each element in the list. In Python, we have the syntax: the keyword for, the loop variable name, the keyword in, and the list to iterate over, followed by a colon. We call this iterating by element versus iterating by index like we did before, because, here, we're not using the index directly.

The for-each loop automatically updates the loop variable to contain the next element in the list on each iteration. So on the first iteration, the loop variable grade will contain the element at index zero. On the second iteration, grade will contain the element at index one and so on and so on until it reaches the end of the list where it automatically terminates the loop.

Note that the loop variable here represents an element of the list, not an index, so we want to make sure we name it descriptively based on what each element represents. Not i. If we move our conditional inside the loop body, we have an equivalent program again.

So, now that we know this, why would we ever want to iterate by index? Behind the scenes, the for-each loop is copying the value of the element into the loop variable. It's not keeping a two-way link back to that location in the list. So, if I want to modify all the values in the list, I can't use a for each loop, All this does is update the value stored in the variable grade.

It doesn't modify the original list. To modify the actual list, the left-hand side of the assignment statement must be a reference to the list itself. That means we need to iterate by index if we want to modify the list. That way, we can use the indices to access specific locations in the list and reassign their values.

Like, maybe the teacher decided to curve every test score by five points. You might also want to iterate by index if the indices of the list are relevant to the calculations, like maybe you only care about every other test score. But whether you're iterating by index or by element, loops give us the power to easily go through every element of a list.

Video © Khan Academy, used under CC BY-NC-SA. Watch on Khan Academy. Puzzicle is not affiliated with Khan Academy.