Since you claim to be used to JavaScript:
The Python in
operator is similar to the JavaScript in
operator.
Here's some JavaScript:
var d = {1: 2, 3: 4};
if (1 in d) {
alert('true!');
}
And the equivalent Python:
d = {1: 2, 3: 4}
if 1 in d:
print('true!')
With objects/dicts, they're nearly identical, both checking whether 1
is a key of the object/dict. The big difference, of course, is that JavaScript is sloppily-typed, so '1' in d
would be just as true.
With arrays/lists, they're very different. A JS array is an object, and its indexes are the keys, so 1 in [3, 4, 5]
will be true
. A Python list is completely different from a dict, and its in
operator checks the values, not the indexes, which tends to be more useful. And Python extends this behavior to all iterables.
With strings, they're even more different. A JS string isn't an object, so you will get a TypeError
. But a Python str
or unicode
will check whether the other operand is a substring. (This means 1 in '123'
is illegal, because 1
can't be a substring of anything, but '1' in '123'
is true.)
With objects as objects, in JS there is of course no distinction, but in Python, objects are instances of classes, not dicts. So, in JS, 1 in d
will be true for an object if it has a member or method named '1'
, but in Python, it's up to your class what it means—Python will call d.__contains__(1)
, then, if that fails, it tries to use your object as an utterable (by calling its __iter__
, and, if that fails, by trying to index it with integers starting from 0
).
Also, note that JS's in
, because it's actually checking for object membership, does the usual JS method-resolution-order search, while Python's in
, because it's checking for keys of a dict, members of a sequence, etc., does no such thing. So, technically, it's probably a bit closer to the hasOwnProperty
method than the in
operator.