Python tutorial (14th) range and xrange

Source: Internet
Author: User

If you need to iterate a digital sequence, you can use the range () function, and the range () function can generate an equal-difference series.
Example:
For I in range (5)
Print (I)
This code will output five numbers: 0, 1, 2, 3, and 4.
Range (10) produces 10 values. You can also start range () from another number, or define a different increment, or even a negative increment.

Range (5, 10) ranges from 5 to 9 (0, 10, 3) increment to three, including 100, -30) the increment is-30, including-10,-40,-70. range () and len () can be used together to iterate an index sequence, for example:

A = ['nina ', 'Jim', 'rainman ', 'Hello']

For I in range (len ()):

Print (I, a [I])

In fact, the principle of python range is to generate an array, and the following method is used:

For I in range (10 ):

Print I

In fact, the range () function is an array and returns the array result to in, that is, it is essentially an iteration.

Xrange
Xrange example:

  1. >>> Xrange (5)
  2. Xrange (5)
  3. >>> List (xrange (5 ))
  4. [0, 1, 2, 3, 4]
  5. >>> Xrange (1, 5)
  6. Xrange (1, 5)
  7. >>> List (xrange (1, 5 ))
  8. [1, 2, 3, 4]
  9. >>> Xrange (0, 6, 2)
  10. Xrange (0, 6, 2)
  11. >>> List (xrange (0, 6, 2 ))
  12. [0, 2, 4]
Through the above example, we can know that xrange in python is different from range in that xrange generates a generator instead of an array.

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.