Thereâs no iterator involved. If you are not detail-oriented, just jump to the bottom for a direct response to your query. Continue from here for more on iteration and iterators.
A bit of terminology: to a first approximation, iteration is stepping through an assemblage of data one item at a time; an iterable is a collection of data through which you can iterate; and an iterator is an object which combines (`âpackagesâ) an iterable with a __next__() method, allowing you to, well, iterate, by calling next().
- A list is an iterable [1,2,3,4]
- The for - in operator turns it into an iterator, and automatically provides the ânextâ. Very convenient!
- But, you can do it yourself, by using iter():
x = [1,2,3,4]
y = iter(x)
print(y)
print(next(y))
print(next(y))
print(next(y))
print(next(y))
print(next(y))
*Output:
<list_iterator object at 0x02FF67D0>
1
2
3
4
Traceback (most recent call last):
File "C:\path\to\test.py", line 9, in <module>
print(next(y))
StopIteration
⌠and oh yes, the for-in operator knows what to do when StopIteration is raised!
All of the above is simply to point out that there is no iterator in a while loop. You can program a while loop to iterate. You can even use while to create an iterator; in fact, thatâs basically how for loops work. ⌠while rules!
But in its essence, a while loop simply tests for a certain condition each time around. It only iterates if you want it to. The variable that you increment might be referred to as an iteration variable, but it is not an iterator.
So what is the answer to your question?
First example: Why not begin with i = 0, then go with
sum += lst[idx]
idx += 1
each time around.
As for the second one, remember that while does not necessarily iterate, it just tests a condition. Remember what pop() does: it removes an item from the end of a list, and returns that item. So If you are popping off one of the students from a list and appending them to another list, all you need to do to get it right is decide how many students you want to move from one list to the other and put that number in the while condition (in this case, the condition is that the length of the new list is less than 6).