Search code examples
pythonpython-3.xiterable

Why use the two-argument form of the `iter` function instead of a while loop?


I came across the iter built-in function in python, which I had never seen used before. The "real-world" example it gives is reading through a large file:

from functools import partial
with open('mydata.db', 'rb') as f:
    for block in iter(partial(f.read, 64), b''):
        process_block(block)

However, it seems like the same effect can be used with a basic while loop without having to use the fancy functions (unless I'm mistaken) --

with open('mydata.db') as f:
    while True:
        block = f.read(50)
        if not block: break
        process_block(block)

What would be the advantage of using the iter method?


Solution

  • The two-argument version of iter is a convenience function that helps in writing more concise code. It has no functional advantage over the equivalent while loop that you included.