[New-bugs-announce] [issue6826] Add __contains__ to range type

Joseph Thomson report at bugs.python.org
Wed Sep 2 22:49:20 CEST 2009


New submission from Joseph Thomson <joseph.thomson at gmail.com>:

The range type should implement the __contains__ method.  Currently an
expression like 'x in range(10000000)' will iterate through every item
in the range (exiting when an item tests true for equality); this is
highly unnecessary as the following expression will perform the same
function in a fraction of the time:

value >= start and value < stop and (value - start) % step == 0

The biggest advantage of this modification would be to allow users to say:

if foo in range(lower, upper):
   bar()

instead of:

if foo >= lower and foo < upper:
   bar()

safe in the knowledge that they are losing no performance.  The former
is also far more Pythonic in my opinion :).

If there is still any doubt (which I doubt), I have attached an example
script showing what is to be gained.

----------
components: Interpreter Core
files: range.py
messages: 92183
nosy: hpesoj
severity: normal
status: open
title: Add __contains__ to range type
type: performance
versions: Python 3.2
Added file: http://bugs.python.org/file14821/range.py

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6826>
_______________________________________


More information about the New-bugs-announce mailing list