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
Also as a side question. 'Not' can be placed in front of a boolean expression, similar to '!' in C or it can be placed in front of the 'in' statement in python. How is this possible?
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'
How are both of these possible? Shouldn't there be a consistency in how they are evaluated? Right now, I believe that it's because Python is an interpreted language, the interpreter can just do different things based on the surrounding syntax.
An explanation or link to an explanation would be super helpful, I've been unable to find anything addressing this.
for <target> in <iterable>
does not have much in common with<expr> in <expr>
other than that both syntaxes use the lettersi
andn
in the same order.not x in array
works too, butnot in
is more readable.in
andnot in
are both operators. As Martijn Pieters said,for … in
is unrelated andin
is not an operator there; instead, it’s part of thefor
syntax. This has nothing to do with Python being an interpreted language.extern
keyword inC
.