Python – Member testing of iterators

Member testing of iterators… here is a solution to the problem.

Member testing of iterators

Can someone explain to me the behavior of the membership test in the last 3 lines of my code, why is it False?
Why are iterators and iterable membership tests different?

c = [1,2,3,4,5,6,7,8,9,10,11,12]

print(3 in c)   # True
print(3 in c)   # True

d = iter(c)
print(2 in d)   # True
print(4 in d)   # True
print(4 in d)   # False  ???
print(6 in d)   # False  ???
print(10 in d)   # False  ???

Solution

Iterators are consumed when in use. I will explain your example:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> print(list(d))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> print(list(d))
[]

You can think of iterator d as a pointer to the first item in the list. Once you read its value, it points to the second item. When it reaches the end, it points to an empty list.

See also:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> print(next(d))
1
>>> print(next(d))
2
>>> print(list(d))
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Check if something in it also consumes its contents:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> 4 in d
True
>>> print(list(d))
[5, 6, 7, 8, 9, 10, 11, 12]

Related Problems and Solutions