Python 3 range Vs Python 2 range

Python 3 uses iterators for a lot of things where python 2 used lists.The docs give a detailed explanation including the change to range.

The advantage is that Python 3 doesn't need to allocate the memory if you're using a large range iterator or mapping. For example

for i in range(1000000000): print(i)

requires a lot less memory in python 3. If you do happen to want Python to expand out the list all at once you can

list_of_range = list(range(10))

in python 2, range is a built-in function. below is from the official python docs. it returns a list.

range(stop)
range(start, stop[, step])
This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops.

also you may check xrange only existing in python 2. it returns xrange object, mainly for fast iteration.

xrange(stop)
xrange(start, stop[, step])
This function is very similar to range(), but returns an xrange object instead of a list.

by the way, python 3 merges these two into one range data type, working in a similar way of xrange in python 2. check the docs.

Tags:

Python

List

Range