range and xrange… which one to use ?

Home Forums Python Programming range and xrange… which one to use ?

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #2065 Reply
    Humble
    Keymaster

    range() and xrange() are syntatically same and both can have 3 arguments where last 2 are optional.

    ‘range(stop) -> list of integers range(start, stop[, step]) -> list of integers..Return a list containing an arithmetic progression of integers.range(i, j) returns [i, i+1, i+2, …, j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement).
    For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements.’

    As said above, range() returns list of output elements..

    For ex:

    >>> range(1,100,10)
    [1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
    >>> 
    
    >>> xobj = xrange(1,10)
    
    >>> for x in xobj:
    ...     print x
    ... 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    
    
    
    
    
    where xrange() returns a generator.. the final or output list is not given back immediately as range() do.. 
    
    Now which one to use and when ?
    
    range() can be a preferred way if you want  to iterate over the list multiple times. If you used  xrange() for this action , it has to generate an integer object every time you access an index.
Viewing 1 post (of 1 total)
Reply To: range and xrange… which one to use ?
Your information: