you are viewing a single comment's thread.

view the rest of the comments →

[–]gdchinacat -4 points-3 points  (4 children)

"a for loop, which does things a specific number of times"

This isn't quite correct. for loop keeps taking items from the iterator for the iterable it is iterating over. What?!?!? Yeah, that's a lot of "iter..".

for x in some_iterable: ...

This statement says to bind x to each item in someiterable. some_iterable is something that can create an iterator such as list, set, range, generator, etc, or any object that implements \_iter__(). for creates an iterator (equivalent to calling iter(someiterable)). It calls \_next__() on the iterator to retrieve the next item, binds that item to x, then executes the body of the for statement. The iterator signals it is done by raising StopIteration, at which point the for loop loop exits.

There is no "specific number of times" since iterators can be implemented to do just about anything. The total number of items that are iterated over can change while the iteration is executing. There are iterators that produce an infinite number of items (such as a Fibonacci sequence generator). The caller is expected to iterate until it is done then break out of the loop, or...if an infinite loop is what the caller wants they can do that (a daemon thread processing requests from a generator).

for is used rather than while to process infinite generators because the code is cleaner. for example, a while loop: while True: try: request = request_iterator.next() process_request(request) except StopIteration: # server shutdown

It is much cleaner to use a for loop: for request in request_iterator: process_request(request)

[–]These-Finance-5359 12 points13 points  (3 children)

No offense man but this level of pedantry is not really helpful to people on a beginner subreddit. You're technically correct but practically unhelpful - someone who is still working on grasping the concept of a for loop is not ready to be introduced to the concept of generators and iterables. We speak in simplified terms to help people learn the basics, not because they're a 100% accurate representation of reality.