In Python 3.x ,
range(0,3)
returns a class of immutable iterable objects that lets you iterate over them, it does not produce lists, and they do not store all the elements in the range in memory, instead they produce the elements on the fly (as you are iterating over them) , whereas list(range(0,3))
produces a list (by iterating over all the elements and appending to the list internally) .
Example -
>>> range(0,3)
range(0, 3)
>>> list(range(0,3))
[0, 1, 2]
Ideally, if you only want to iterate over that range of values , range(0,3)
would be faster than (list(range(0,3))
because the latter has the overhead of producing a list before you start iterating over it.
In Python 2.x , range(0,3)
produces an list, instead we also had an xrange()
function that has similar behavior of range()
function from Python 3.x (xrange was renamed to range in Python 3.x)
For Python 3.5, From the documentation -
Range objects implement the collections.abc.Sequence ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices
So you can do things like -
>>> range(0,10)[5]
5
>>> range(0,10)[3:7]
range(3, 7)
>>> 5 in range(6,10)
False
>>> 7 in range(1,8)
True
And all of these are constant time operations , as can be seen from this test -
In [11]: %timeit a = xrange(0,1000000)[1000]
1000000 loops, best of 3: 342 ns per loop
In [12]: %timeit a = xrange(0,1000000)[10000]
1000000 loops, best of 3: 342 ns per loop
In [13]: %timeit a = xrange(0,1000000)[100000]
1000000 loops, best of 3: 342 ns per loop
In [14]: %timeit a = xrange(0,1000000)[999999]
1000000 loops, best of 3: 342 ns per loop
In [15]: %timeit a = xrange(0,10000000)[9999999]
1000000 loops, best of 3: 339 ns per loop
In [16]: %timeit a = xrange(0,1000000000000)[9999999999]
1000000 loops, best of 3: 341 ns per loop