NEWBIE: Extending a For Statement.

Dustan DustanGroups at gmail.com
Mon May 21 18:12:18 EDT 2007


On May 21, 9:21 am, mosscliffe <mcl.off... at googlemail.com> wrote:
> On 21 May, 15:02, bearophileH... at lycos.com wrote:
>
> > mosscliffe:
>
> > > if key in xrange (60,69) or key == 3:
>
> > I keep seeing again and again code like this, mostly from people not
> > much expert of Python, but the PEP 260 shows the fast in was removed,
> > so it's O(n). Maybe removing the fast __contains__ was bad for
> > necomers (or just the casual Python users, that I belive is really
> > large).
>
> > Bye,
> > bearophile
>
> Being a non-expert in python in fact just a beginner / casual user,
> can you expand on how 0(n) relates to
>     if key in xrange (60,69) or key == 3:

the "key in xrange(60,69)" part: all that does is iterate through
xrange(60, 69) and when a match is met, it returns true. If it ends up
iterating through the whole list without finding a match, it returns
false.

> My mind tends to go blank at the mention of __xxx__.

The above is the default behavior of the 'in' operator. That default
behavior can be overridden by a class that has the __contains__
method. So "XXX in YYY" expands roughly to the following (as I
understand it; I haven't actually looked it up):

if hasattr(YYY, "__contains__"):
    return YYY.__contains__(XXX)
else:
    for i in YYY:
        if XXX == YYY:
            return True
    return False

> R




More information about the Python-list mailing list