Question: When using list comprehension or the `in` keyword in a for loop context, i.e:

```
for o in X:
    do_something_with(o)

```

or

```
l=[o for o in X]

```

* How does the mechanism behind `in` works?
* Which functions\methods within `X` does it call?
* If `X` can comply to more than one method, what's the precedence?
* How to write an efficient `X`, so that list comprehension will be quick?

Answer: 
`X` must be iterable. It must implement `__iter__()` which returns an iterator object; the iterator object must implement `next()`, which returns next item every time it is called or raises a `StopIteration` if there's no next item.

Lists, tuples and generators are all iterable.

Note that the plain `for` operator uses the same mechanism.
Answering question's comments I can say that reading source is not the best idea in this case. The code that is responsible for execution of compiled code ([ceval.c](http://svn.python.org/view/python/trunk/Python/ceval.c?view=markup)) does not seem to be very verbose for a person that sees Python sources for the first time. Here is the snippet that represents iteration in for loops:

```
   TARGET(FOR_ITER)
        /* before: [iter]; after: [iter, iter()] *or* [] */
        v = TOP();

        /*
          Here tp_iternext corresponds to next() in Python
        */
        x = (*v->ob_type->tp_iternext)(v); 
        if (x != NULL) {
            PUSH(x);
            PREDICT(STORE_FAST);
            PREDICT(UNPACK_SEQUENCE);
            DISPATCH();
        }
        if (PyErr_Occurred()) {
            if (!PyErr_ExceptionMatches(
                            PyExc_StopIteration))
                break;
            PyErr_Clear();
        }
        /* iterator ended normally */
        x = v = POP();
        Py_DECREF(v);
        JUMPBY(oparg);
        DISPATCH();

```

To find what actually happens here you need to dive into bunch of other files which verbosity is not much better. Thus I think that in such cases documentation and sites like SO are the first place to go while the source should be checked only for uncovered implementation details.