[Tutor] range efficiency

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri May 10 23:27:44 CEST 2013


Jim Mooney wrote:
> If I'm using a variable-dependent range in a for loop, is Python smart
> enough to figure the variable once so I don't have to hoist it up?
> 
> That is for c in range(0,x+2), is x+2 figured once or every time
> through the loop? I'm assuming it's once but I like to verify.
> 
> I'll figure this myself once I get an editor I like with a profiler,
> but I'm still trying editors and don't want to spend all my time on
> them. So far I'm in between too simple, overkill, or buggy. And I
> don't want anything that uses Java. I'm allergic to Java ;')
> 
> --
> Jim Mooney
> 
> "For anything that matters, the timing is never quite right, the
> resources are always a little short, and the people who affect the
> outcome are always ambivalent."

x+2 is only calculated once and then passed to range. The for loop
then iterates over the range object. It is not recreating/re-calling
range(). 

Note in python 2 you should use xrange as it is a generator and 1. lazy 
2. more memory efficient. Unlike Python 2, in Python 3 range is a 
generator.


~Ramit




This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list