Reputation: 3109
I recently came across some python code I don't understand completely.
s = "abcdef"
x = "bde"
it = iter(s)
print all(c in it for c in x)
I understand that this code checks if x is a subsequence of s. Can someone explain or point me towards an article that explains what's exactly happening at c in it
. What is calling the next method of iterator it
?
Upvotes: 0
Views: 62
Reputation: 9140
It’s good to start with reading the documentation for the built-in function all()
:
Return True if all elements of the iterable are true (or if the iterable is empty).
That means that c in it for c in x
is a “generator expression”: it produces values. The values it produces are of the boolean expression c in it
(see the in
operator) for all characters c
in string x
.
Here, the in
operator is responsible for advancing the iterator. Note, however, that the True result is probably lucky. The iterator it
can advance only once and because x = "bde"
contains the letters in the same sequence as they appear in s = "abcdef"
, the whole expression works out to the expected result True. Reverse x = "edb"
and the expression is False because the iterator is exhausted.
Upvotes: 1