When called with two arguments, iter takes on the value being called and given. This behavior looks like it was implemented like this:
def iter2args(f, sentinel): value = f() while value != sentinel: yield value value = f()
What is passed as f must be called, which means you can name it as a function. The built-in list type object that you use to create new instances of the list by calling it as a function:
>>> list('abcde') ['a', 'b', 'c', 'd', 'e']
The list l that you passed in is an existing instance of the list that cannot be used as a function:
>>> l = [1,2,3,4,5,6] >>> l(3) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> l(3) TypeError: 'list' object is not callable
Thus, there is a big and important difference between list objects and list instances that appear when used with iter .
To iterate the list until the watch is reached, you can use itertools.takewhile :
import itertools for val in itertools.takewhile(l, lambda x: x!= 4): print(val)
Michael J. Barber
source share