Python iterators and generators (yield)

Source: Internet
Author: User
Tags arithmetic

I. List all built-in functions

Stamp: https://docs.python.org/2/library/functions.html

Two, range, xrange (iterator)

Both range () and xrange () are built-in functions in Python. This two built-in function is most commonly used in a for loop. For example:

    1. >>> for I in range (5):
    2. ... print I
    3. ...
    4. 0
    5. 1
    6. 2
    7. 3
    8. 4
    9. >>> for I in Xrange (5):
    10. ... print I
    11. ...
    12. 0
    13. 1
    14. 2
    15. 3
    16. 4
    17. >>>

Range () and xrange () are two different implementations in Python 2. However, in Python 3, the implementation of range () is removed;
The implementation of the Xrange () is preserved and the Xrange () is renamed to Range ().

First, let's look at Python 2 range (). It is a built-in function that is used to create integer arithmetic progression. So it
is often used for a for loop. Below is the official Help document for range ().

    1. Help on built-in function range in module __builtin__:
    2. range (...)
    3. Range (stop), List of integers
    4. Range (Start, stop[, Step), List of integers
    5. Return A list containing an arithmetic progression of integers.
    6. Range (I, j) returns [I, I+1, i+2, ..., j-1]; start (!) defaults to 0.
    7. when step is given, it specifies the increment (or decrement).
    8. For example, range (4) returns [0, 1, 2, 3]. The end point is omitted!
    9. These is exactly the valid indices for a list of 4 elements.
    10. (END)

From the official help document, we can see the following features:
1. Built-in function (built-in)
2, accept 3 parameters are start, stop and step (where start and step are optional, stop is required)
3. If start is not specified, the default starts at 0 (Python starts from 0)
4. If no step is specified, the default step is 1. (Step cannot be 0, if you specify step 0, "valueerror:range () step argument must not is zero"
will be thrown.
Additional Features:
1, when step is positive, start should be less than stop, otherwise will generate [], that is, empty sequence.

    1. >>> Range (-3)
    2. []
    3. >>> Range (5, 1)
    4. []
    5. >>> Range (+)
    6. []

2, when step is negative, start should be greater than stop, otherwise will generate [], that is, empty sequence.
These two features explain that range () can generate a sequence of increments and decrements.
The following is an example of a range () generation sequence:

    1. >>> Range (5)
    2. [0, 1, 2, 3, 4]
    3. >>> Range (1,8,3)
    4. [1, 4, 7]
    5. >>> Range (0,-10)
    6. []
    7. >>> Range (0,-10,-2)
    8. [0,-2,-4,-6,-8]
    9. >>>

Next look at Xrange (). Xrange () is a built-in function, but it is defined as a type in Python,
This type is called xrange. We can easily see this in the Python 2 interactive shell.

    1. >>> Range
    2. <built-in function range>
    3. >>> xrange
    4. <type ' xrange ' >
    5. >>>

Let's take a look at Xragne's official help document:

  1. Help on the class xrange in module __builtin__:
  2. Class Xrange (Object)
  3. | Xrange (stop), xrange object
  4. | Xrange (Start, stop[, step), xrange object
  5. |
  6. | Like range (), but instead of returning a list, returns an object that
  7. | Generates the numbers in the range on demand. For looping
  8. | Slightly faster than range () and more memory efficient.
  9. |
  10. | Methods defined here:
  11. |
  12. | __getattribute__ (...)
  13. | x.__getattribute__ (' name ') <==> x.name
  14. |
  15. | __getitem__ (...)
  16. | x.__getitem__ (y) <==> X[y]
  17. |
  18. | __iter__ (...)
  19. | X.__ITER__ () <==> iter (x)
  20. |
  21. | __len__ (...)
  22. | x.__len__ () <==> len (x)
  23. |
  24. | __reduce__ (...)
  25. |
  26. | __repr__ (...)
  27. | x.__repr__ () <==> repr (x)
  28. |
  29. | __reversed__ (...)
  30. | Returns a reverse iterator.
  31. |
  32. | ----------------------------------------------------------------------
  33. | Data and other attributes defined here:
  34. |
  35. | __new__ =
  36. | T.__NEW__ (S, ...)-A new object with type S, a subtype of T
  37. (END)

As you can see from the documentation, the parameters and usages of xrange and range are the same. Just Xrange () returned is no longer a sequence, but a
The Xrange object. This object can generate numbers (that is, elements) within the specified range of parameters as needed. Because the Xrange object is generated on demand, a single
element, instead of creating the entire list first, as in range. So, within the same range, xrange occupies less memory space and xrange
will also be faster. In fact, Xrange generates an element because it is called within a loop, so no matter how many times it is looped, only the current element
Takes up memory space, and each cycle consumes the same single element space. We can roughly think that, with the same n elements, range accounts for
The space used is n times the xrange. Therefore, in a large cycle, the efficiency and speed of the xrange will be apparent. We can use Timeit.
To test the execution time of range and xrange.

    1. >>> Timeit.timeit (' For I in Range (10000000): Pass ', number=1)
    2. 0 . 49290895462036133
    3. >>> Timeit.timeit (' For I in Xrange (10000000): Pass ', number=1)
    4. 0 . 2595210075378418

Under the condition of a lot of cycles, it is obvious that the efficiency of xrange can be seen.

To summarize:
1, Range () returns the entire list.
2, Xrange () returns a Xrange object, and this object is a iterable.
3. Both are used with the For loop.
4. Xrange () takes up less memory space because xrange () only generates the current element at loop time, unlike the range () to generate a complete list at the beginning.
This is the same point and difference between range and xrange in Python 2.

So in Python 3, we mentioned earlier that range () was removed and Xrange () was renamed to Range (). Are there any differences between them?
Take a look at the following code
Python 2 xrange ()

  1. Python 2.7.6 (Default, Dec 5 2013, 23:54:52)
  2. [GCC 4.6.3] on linux2
  3. Type "Help", "copyright", "credits" or "license" for more information.
  4. >>> x = xrange (5)
  5. >>> x
  6. Xrange (5)
  7. >>> x[:]
  8. Traceback (most recent):
  9. File "", Line 1, <module>
  10. Typeerror:sequence index must is integer, not ' slice '
  11. >>> X[-1]
  12. 4
  13. >>> list (x)
  14. [0, 1, 2, 3, 4]
  15. >>> dir (x)
  16. [' __class__ ', ' __delattr__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __getitem__ ', ' __hash__ ', ' __init__ ', ' __ Iter__ ', ' __len__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __reversed__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ']
  17. >>>

Range of Python 3 ()

  1. Python 3.3.4 (Default, Feb 23 2014, 23:07:23)
  2. [GCC 4.6.3] on Linux
  3. Type "Help", "copyright", "credits" or "license" for more information.
  4. >>> x = Range (5)
  5. >>> x
  6. Range (0, 5)
  7. >>> x[:]
  8. Range (0, 5)
  9. >>> X[:3]
  10. Range (0, 3)
  11. >>> list (x)
  12. [0, 1, 2, 3, 4]
  13. >>> X[-1]
  14. 4
  15. >>> dir (x)
  16. [' __class__ ', ' __contains__ ', ' __delattr__ ', ' __dir__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __ge__ ', ' __getattribute__ ' ', ' __getitem__ ', ' __gt__ ', ' __hash__ ', ' __init__ ', ' __iter__ ', ' __le__ ', ' __len__ ', ' __lt__ ', ' __ne__ ', ' __new__ ', ' __re duce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __reversed__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' Count ', ' index ', ' start ' , ' step ' , ' Stop ' ]
  17. >>>

Obviously, Range object adds a new attributes to Python,' Count ',' index ', ' Start ',' Step ',' Stop '
and can support slicing. The range () of Python 3 becomes more powerful on the basis of xrange ().

Please understand the following phrase:
The Advantage of theRangetype over a regularListortupleIS, aRangeObject would always take the same (small) amount of memory, no matter the size of the range it represents (as it is only Stores the start, stop and step values, calculating individual Items and subranges as needed).

Here, we should be more clear about the difference between range and xrange.

Python iterators and generators (yield)

Related Article

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.