I studied predominantly in C and spent a lot of time understanding its implementation under the hood. But I've recently begun learning python. So there are a lot of quirks here different from C.
How does the 'in' statement work in python?
if x in array:
#the usage of an in statement produces a boolean
for x in array:
#the usage of an in statement produces an iterable
if not x == 5:
#makes sense because 'x == 5' evaluates to a boolean
if x not in array:
#the statement 'in array' is not a boolean
#shouldn't it be 'if not x in array'
You are confusing two totally unrelated pieces of syntax.
One is a statement, see the
for statement documentation. The
in is part of the fixed grammar:
for_stmt ::= “for” target_list “in” expression_list “:” suite [“else” “:” suite]
The moment you use
for to start a line, the
in part is required, just as the
: is required. And don't confuse Python's
for with a C
for loop; Python's is a For Each construct. As such it doesn't 'produce' an iterable, it requires an iterable as input.
The other is a membership test operation, and operators are a type of expression:
not intest for membership.
It is meant to apply to containers (not just iterables).
Both are leaning heavily on Python's OO nature, something C can't do. If you want to find equivalents in other languages, look at concepts in C++, Java or C#, not at C.
<expr> [not] in <expr> only requires that the right-hand expression result supports membership testing, but Python will fall back to iteration if no explicit hooks are available for a membership test. The
not in simply inverts the result of the
C++ and Java have no standard abstraction for this, different container types each implement their own spelling (in C++ most call it
map::find, while Java usually picks
contains variations, giving you