Why or why not?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For performance, especially when you’re iterating over a large range,
xrange()is usually better. However, there are still a few cases why you might preferrange():In python 3,
range()does whatxrange()used to do andxrange()does not exist. If you want to write code that will run on both Python 2 and Python 3, you can’t usexrange().range()can actually be faster in some cases – eg. if iterating over the same sequence multiple times.xrange()has to reconstruct the integer object every time, butrange()will have real integer objects. (It will always perform worse in terms of memory however)xrange()isn’t usable in all cases where a real list is needed. For instance, it doesn’t support slices, or any list methods.[Edit] There are a couple of posts mentioning how
range()will be upgraded by the 2to3 tool. For the record, here’s the output of running the tool on some sample usages ofrange()andxrange()As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.