[Tutor] check_range

Jeff Shannon jeff at ccvcorp.com
Wed Dec 15 01:23:39 CET 2004


Jeff Shannon wrote:

>> if myrange in range(10,90):  # "in" is the key word here
>>     return True
>> else
>>     return False
> 
> 
> This is, however, the correct solution. :)  

Or I *should* say, rather, that this is *a* correct solution, in that 
it will yield the expected answer.  Kent Johnson's '10 < x < 90' is a 
better solution, however -- 'if x in range(...)' creates a list of 
numbers, and then steps through that list comparing x to each one in 
turn, while Kent's version makes only two comparisons and no object 
creations.  While one should never prematurely optimize, it's also 
good to be aware of how much work is done by different options, and in 
this case 'if x in range()' isn't any clearer than the direct 
comparisons.  I'd think nothing of the extra cost of using range() if 
it *did* make the code easier to read, but there's no sense in going 
to extra work for no benefit.  :)

Jeff Shannon
Technician/Programmer
Credit International



More information about the Tutor mailing list