Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking elements' existence within an iterator in python

When we are using an iterator, the elements pops out by order, then how do we check if a guessing element within the iterator or not? In my code only in seems to work:

t = "cawqv"
it = iter(t)

print(next(it))
print("a" in it)
print("w" is it) 
print("w" == it)
print("w" in it)
>>
c
True
False
False
True

is is unlikely to work in the case since it checks whether two objects are the same object, but == only cares their value, like equals() method in Java. Is the in operator the only one we can use to check element existence within an iterator?


1 Answers

"w" == it is checking if w (a string) equals your iterator which is obviously False as your iterator encapsulates a sequence which may or may not contain w. To check for existence of an element using equality you'll have to actually iterate over your iterator and then check if any of the elements encountered during the iteration equals your search element, i.e.:

print(any(i == "w" for i in it))

but that's what print("w" in it) internally does, anyway. Keep in mind that the above will exhaust (partially on match, completely if the element is not matched) your iterator, just like "w" in it does, because you need to iterate over an iterator to determine if any of the elements matches your search element, e.g.

t = "cawqv"
it = iter(t)
print("w" in it)  # True
print("w" in it)  # False - we're pass the `w` point by now
print("q" in it)  # False - we already exhausted our iterator
like image 186
zwer Avatar answered Mar 03 '26 06:03

zwer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!