Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

xrange vs _ in range

_ in range was used in the datetime course - for a more memory efficient loop. How does this differ from xrange - which I've heard is used for a similar purpose?

3 Answers

xrange() apparently does not exist in python 3., but range() does what it used to do (discussed here).

Anyway, I don't know if this is more to the point of your question, but what, for example, for _ in range(n) does is perform the code inside the code block once for every element in the range, but doesn't bother to store the value, thus saving precious memory. I don't know the internals, but there it is.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Mikael Enarsson has it right. It's more memory-efficient because it doesn't store the current value of the loop. In Python 2, most of the time you wanted to use xrange() because it's a generator instead of a list, like range() was. In Python 3, plain ol' range() is a generator so there's no reason to use (or even have) xrange().

Ok thanks for the explanations - I need to go and find out more about generators (vs iterators) as I haven't really covered what they are yet.

Thanks.