Python built-in functions and python built-in functions

Source: Internet
Author: User
Tags builtin

Python built-in functions and python built-in functions

1. List all built-in functions

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

2. range and xrange (iterator)

Both range () and xrange () are built-in functions in Python. These two built-in functions are most commonly used in the 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. But in Python 3, range () is removed;
Retain the implementation of xrange () and rename xrange () to range ().

First, let's look at range () in Python 2 (). It is a built-in function that is used to create an integer equal-difference series. So it
It is often used for a for loop. The following is an 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 sion ssion of integers.
  6. Range (I, j) returns [I, I + 1, I + 2,..., J-1]; start (!) Ults 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 are exactly the valid indices for a list of 4 elements.
  10. (END)

From the official help documentation, we can see the following features:
1. built-in functions (built-in)
2. Accept three parameters: start, stop, and step (where start and step are optional and stop are required)
3. If start is not specified, start from 0 by default (Python starts from 0)
4. If no step is specified, the default step is 1. (Step cannot be 0. If the specified step is 0, "ValueError: range () step argument must not be zero"
Will be thrown.
Additional features:
1. When step is a positive number, start should be smaller than stop; otherwise, [] will be generated, that is, an empty series.

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

2. When step is negative, start must be greater than stop. Otherwise, [] is generated, that is, an empty sequence.
These two features indicate that range () can generate ascending and descending series.
The following is an example of a series generated by range:

  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 let's take a look at xrange (). Although xrange () is also a built-in function, it is defined as a type in Python ),
This type is called xrange. We can easily see this in the interactive shell of Python 2.

  1. >>> Range
  2. <Built-in function range>
  3. >>> Xrange
  4. <Type 'xrange'>
  5. >>>

Let's take a look at xragne's official help documentation:

  1. Help on 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, this is
  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)

The document shows that the parameters and usage of xrange and range are the same. Only xrange () does not return a series, but
Xrange object. This object can generate numbers (elements) within the specified range of parameters as needed ). Because xrange objects generate a single
Instead of the range, create the entire list first. Therefore, in the same range, xrange occupies less memory.
It will be faster. In fact, xrange generates elements only when called in a loop. Therefore, no matter how many times the current element is recycled
Memory space is occupied, and each cycle occupies the same single element space. We can roughly think that if n elements are the same, range occupies
The used space is n times that of xrange. Therefore, in the case of a large loop, the efficiency and speed of xrange will be obvious. 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

In the case of a large number of loops, we can see that the efficiency of xrange is obvious.

Summary:
1. range () returns the entire list.
2. xrange () returns an xrange object, which is an iterable object.
3. Both use the for loop.
4. xrange () occupies less memory space, because xrange () generates only the current element in a loop, unlike range (), which generates a complete list at the beginning.
This is the similarities and differences between range and xrange in Python 2.

In Python 3, we mentioned previously that range () is removed, and xrange () is renamed to range (). Are there any differences between them?
See the following code.
Xrange () of Python 2 ()

  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 call last ):
  9. File "", line 1, in <module>
  10. TypeError: sequence index must be 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 _', '_ performance_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 _', '_ ins INS _', '_ delattr _', '_ dir __', '_ doc _', '_ eq _', '_ format _', '_ ge _', '_ getattribute __', '_ getitem _', '_ gt _', '_ hash _', '_ init _', '_ iter __', '_ le _', '_ len _', '_ lt _', '_ ne _', '_ new __', '_ reduce _', '_ performance_ex _', '_ repr _', '_ reversed _', '_ setattr __', '_ sizeof _', '_ str _', '_ subclasshook __','Count', 'Index', 'Start', 'Step', 'Stop']
  17. >>>

Obviously, range object adds a new attributes in Python,'Count', 'Index', 'Start', 'Step', 'Stop',
Slicing is supported. The range () of Python 3 is more powerful on the basis of xrange.

Please understand the following sentence:
The advantage ofRangeType over a regularListOrTupleIs thatRangeObject will always take the same (small) amount of memory, no matter the size of the range it represents (as it only storesStart,StopAndStepValues, calculating individual items and subranges as needed ).

Here, we should know the difference between range and xrange.

Iii. yield

Def fab (max): n, a, B = 0, 0, 1 while n <max: yield B # print B a, B = B, a + B n = n + 1c = fab (10) print (c. _ next _ () # python 3.x has no next () method print (c. _ next _ () print (c. _ next _ () print (c. _ next _ () # for I in fab (10): # print (I)

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.