Usage analysis of xrange in python

  • 2020-05-10 18:22:48
  • OfStack

This article illustrates the use of xrange in python as an example. Share with you for your reference. The details are as follows:

Let's start with the following example:


>>> x=xrange(0,8)
>>> print x
xrange(8)
>>> print x[0]
0
>>> print x[7]
7
>>> print x[8]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
IndexError: xrange object index out of range
>>> x=range(0,8)
>>> print x
[0, 1, 2, 3, 4, 5, 6, 7]
>>> print x[0]
0
>>> print x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
range([start,] stop [,step])->list of integers

range() returns a list of incrementing or decrementing Numbers whose element values are determined by three parameters

start represents the value at the beginning of the list, which defaults to "0."

stop represents the value at the end of the list and is indispensable

The parameter step represents the step size, with a default value of "1".

range() returns a list of increasing or decreasing Numbers.

xrange is a class that returns an xrange object. Traversing using xrange() returns only one value at a time. range() returns a list, evaluated once and returns all values. Therefore, the efficiency of xrange() is higher than that of range().

I hope this article is helpful for you to design Python program.


Related articles: