not in

Raymond Hettinger othello at javanet.com
Mon Jan 28 00:04:36 EST 2002


"Michael Robin" <me at mikerobin.com> wrote in message
news:52e5ab5f.0201211338.b171820 at posting.google.com...
> Neal Norwitz <neal at metaslash.com> wrote in message
> > rihad wrote:
> > However, 'not x in s' should equal 'x not in s'.
> >
> > Use whichever is clearer to you.  I prefer x not in s, because that's
> > how I use it in English and how I think.
>
> They should evaluate equal, but you'd think you could choose
> one over the other based on wether you expected the item
> to normally be in the sequence (early) or not, as "not x in s"
> should drop out faster than "x not in x" if you expect
> one or more x's to be present, and conversely. (I just verified
> this with list of len==1000000 in a loop.)
> Probably not an issue for any but the most heinous instantiated
> sequences, but for getitem()s/iter()s it could be a realizable savings.

Not really.

I re-created the test and found no speed difference between 'x in s',
'x not in s', and 'not x in s'.  See test suite and results below.

its-not-what-you-know-but-what-you-know-that-aint-so-ly yours,

Raymond




import time, random
def test( elem, seqn, cnt ):
    gettime = time.time
    cum1 = cum2 = cum3  = 0.0
    for i in xrange(cnt):
        start = gettime()
        x = elem in seqn
        cum1 += gettime() - start

        start = gettime()
        x = elem not in seqn
        cum2 += gettime() - start

        start = gettime()
        x = not elem in seqn
        cum3 += gettime() - start
    print cum1, cum2, cum3

seqn = [ random.randint(0,6) for i in xrange(200000) ]
test( 4, seqn, 1000 )  # 4 occurs early in the sequence
test( 9, seqn, 1000 )  # 9 does not occur

0.0 0.0499999523163 0.120000123978
26.5100008249 26.8499991894 26.7200000286





More information about the Python-list mailing list