got net?

Kevin Hazzard's Brain Spigot

About the author

Welcome to Kevin Hazzard's blog.
E-mail me Send mail

Recent posts

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

PyTip: Avoid Using range() for Large Sequences

When iterating over a sequence of numbers in Python, the range() function is commonly used. However, the implementation of the range() function in Python 2.x instantiates each element in the sequence before the iteration begins. This is really costly from both memory and CPU perspectives when the desired range of numbers is large. Consider using the xrange() function instead which implements a Python generator to yield each number in the sequence as needed. Using xrange() instead of range() for large iterations can have a big, positive impact on your code. For example, in an application I was working on recently, replacing range() calls with xrange() boosted my performance from ~900,000 transactions per second to over 3,000,000. In Python 3.x, the range() function is supposed to be implemented as a generator but I haven't tested that to be true yet. Let me know if you have.


Posted by kevin on Monday, September 21, 2009 7:00 AM
Permalink | Comments (4) | Post RSSRSS comment feed

Comments

Ron DuPlain United States

Friday, September 25, 2009 11:19 AM

Ron DuPlain

Indeed, Python 3.x uses range with a generator. xrange no longer exists, and the 2to3 tool replaces xrange with range.

docs.python.org/.../3.0.html

-Ron

Kevin Hazzard United States

Friday, September 25, 2009 12:45 PM

Kevin Hazzard

Thanks, Ron. I haven't been working with 3.x much yet. I suppose I am not alone in finding it odd that 2.6 is still in progress and gaining acceptance in the marketplace while 3.x is already in production. I need to do some research on the 2to3 tool before I start converting all my code. Thanks.

clear choice dental implants United States

Tuesday, October 13, 2009 11:42 PM

clear choice dental implants

Thanx for the effort, keep up the good work Great work, I am going to start a small Blog Engine course work using your site

Nosdo United States

Wednesday, October 14, 2009 12:00 AM

Nosdo

Thanks for posting about this, I would love to read more about this topic.

Comments are closed