Iteration, while loop, and for loop
Tim Chase
python.list at tim.thechases.com
Tue Jun 28 13:23:08 EDT 2016
On 2016-06-29 01:20, Steven D'Aprano wrote:
> While loops are great for loops where you don't know how many
> iterations there will be but you do know that you want to keep
> going while some condition applies:
>
> while there is still work to be done:
> do some more work
I find this particularly the case when the thing being iterated over
can be changed, such as a queue of things to process:
items = deque()
items.append(root_node)
while items:
item = items.popleft()
process(item)
items.extend(item.children)
Using a "for" loop balks if you try to change the thing over which
you're iterating.
But then, if you wrap up your "while" loop as a generator that yields
things, you can then use it in a "for" loop which seems to me like
the Pythonic way to do things. :-)
-tkc
More information about the Python-list
mailing list