when is filter test applied?
Peter Otten
__peter__ at web.de
Tue Oct 3 11:45:14 EDT 2017
Neal Becker wrote:
> In the following code (python3):
>
> for rb in filter (lambda b : b in some_seq, seq):
> ... some code that might modify some_seq
>
> I'm assuming that the test 'b in some_seq' is applied late, at the start
> of each iteration (but it doesn't seem to be working that way in my real
> code), so that if 'some_seq' is modified during a previous iteration the
> test is correctly performed on the latest version of 'some_seq' at the
> start of each
> iteration. Is this correct, and is this guaranteed?
Yes. filter() is lazy in Python 3, and otherwise the usual rules for
binding, mutating, and lookup of some_seq apply. Example:
>>> some_seq = set("abc")
>>> for c in filter(lambda x: x in some_seq, "abbbcccCBBBBAAA"):
... some_seq.remove(c)
...
>>> some_seq = set("abc")
>>> for c in filter(lambda x: x in some_seq, "abbbcccCBBBBAAA"):
... print(c)
... some_seq.remove(c)
... if not some_seq: some_seq = set("ABC")
...
a
b
c # at that point some_seq will be bound to a new set("ABC")
C
B
A # as above
A
More information about the Python-list
mailing list