Range and Xrange

Source: Internet
Author: User

Range is used exactly the same as xrange, and the difference is that the return result is different: Range returns a list, and Xrange returns a generator. can look at the

1 Print type (range (5))23print type (xrange (5))45  6# print Result: <type ' list ' >7#         <type ' Xrange ' >

You can see that their return type is not the same, one is a list, one is xrange, that is, the range returns need to open up a memory space to store the list, and Xrange is the return of each call one of the values, that is, by an algorithm to calculate the subsequent values, This avoids the need to create a full list.

1 Print range (5)23# printing results: [0, 1, 2, 3, 4]45 Print xrange (5)67# Printing results: xrange (5)

As you can see, Range creates a complete list, and xrange is not. The benefit of xrange is that it consumes less memory and is more efficient than range, especially when it needs to be back very large. Here's a look at the code:

1 Import Time2 3 defrange_time ():4Time1 =time.time ()5      forIinchRange (0, 1000000):6         Pass7Time2 =time.time ()8     PrintTime2-time19 Ten defxrange_time (): OneTime1 =time.time () A      forIinchXrange (0, 1000000): -         Pass -Time2 =time.time () the     PrintTime2-time1 -  - range_time () - xrange_time () +  - #Print Result: 0.0380001068115 + #0.0179998874664

You can see that range execution time is 0.0380001068115,xrange to 0.0179998874664,xrange efficiency is significantly higher than range, so try to use xrange unless you need to return a list.

Note: Python has no range in the 3.x version and has changed xrange to range.

Range and Xrange

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.