1

I know that the in operator can be used in Python as a short-hand of the following (generally speaking, not considering any hidden equality issues or anything):

for item in list1:
    if item == thingToCheck:
        return True
return False

However, I was wondering about the technical meaning of in in the actual for item in list1 line- obviously there is another meaning to in, since Python wouldn't generate every single possible value of item and see if item in list1. On a related note, are Python for loops ever made without in?

SimonT
  • 2,219
  • 1
  • 18
  • 32

2 Answers2

4

in calls the __contains__ method (of list in this case)

For list and tuple this is linear search

For dict and set it uses a hash

When used in a for loop, in just means take the next item from the iterable until it runs out.

You can imagine it's something like this

it = iter(list1)
while True:
    try:
        item = next(it)
    except StopIteration:
        break
    if item == thingToCheck:
        return True
return False 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Good explanation. I'd still really like to know about `for` loops without `in` in them. So can I presume that Python does something like "overriding" the `in` keyword to fit these very different uses? – SimonT Aug 15 '13 at 03:53
  • 4
    @Tangmeister: I don't believe you'll find a `for` loop without using `in`. Note that when used in a `for` loop line, the `in` doesn't mean the same thing as when it's used in an expression. – Greg Hewgill Aug 15 '13 at 03:55
  • Yes, some keywords have different meanings depending on their context. This is partly to avoid having too many keywords – John La Rooy Aug 15 '13 at 03:55
2

No, you won't find a for loop without in, because it is syntactically necessary, see Python language reference. As Greg pointed out, the fact, that the same keyword is used, does not mean, that the internal processing is similar let alone identical. Similar is the never-dying discussion concerning programming languages, where = has the two roles of assignment and as comparison operator. Programming languages are designed for readability and to abstract from what is actually happening, and the abstraction increases with the level of the language.

guidot
  • 5,095
  • 2
  • 25
  • 37