Python's range and xrange

Source: Internet
Author: User
Tags generator

Range

Function Description: Range ([Start,] stop[, step]), which generates a sequence based on the range specified by start and stop and step set by step.

Range Example:

>>> Range (6) [0, 1, 2, 3, 4, 5]>>> Range (0,6,2) [0, 2, 4]
Xrange

Function Description: Syntactically and range exactly the same, the difference is not an array is generated, but a generator.
xrange Example:

>>> xrange (6) xrange (6) >>> list (xrange (6)) [0, 1, 2, 3, 4, 5]>>> xrange (0,6,2) xrange (0, 6, 2) & Gt;>> list (xrange (0,6,2)) [0, 2, 4]

Range and xrange are used more in the loop, and the following is an analysis of their respective performance in the loop:

If the loop is in range, we can see from the above result that an array will be generated. If the number of elements is less acceptable, but if the number of elements is very large, it is not to open up a lot of memory to store this array? This pair makes memory space for Alexander.

If you use Xrange,xrange to return a generator, you can return one value at a time, so you don't have to open up so much memory space.

So, try to use xrange in the loop, as the number of elements increases, xrange performance is much better than range.

Note that in python3.x, xrange is abolished, and the range function is the same as xrange.

Python's 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.