Range Python 3 Vs Python 2

I recently started learning python 3.
In python 2 function, range()

list items can be assigned.

>>> A = []
>>> A = range(0,6)
>>> print A
[0, 1, 2, 3, 4, 5]

      

where as in python 3 when a function is used range()

this happens

>>> A = []
>>> A = range(0,6)
>>> print(A)
range(0, 6)

      

Why is this happening?
why did python make this change?
Is this a blessing or a curse?

+3


source to share


4 answers


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

.

The advantage is that Python 3 doesn't need to allocate 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 really need Python to expand the list right away, you can

list_of_range = list(range(10))

      

+8


source


in python 2, range

is a built-in function. below are the official python docs . it returns a list.

Range (stop)
range (start, stop [, step])
This is a versatile function for creating lists containing arithmetic progressions. It is most commonly used for loops.

also you can xrange

only check existing in python 2. it returns an object xrange

, mostly for fast iteration.



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

by the way, python 3 combines these two into one data type range

, working in a similar way xrange

in python 2. check docs .

+2


source


Python 3 range()

function is equivalent to python 2 xrange()

not functionrange()

Explanation

In python 3, most functions return Iterable objects rather than lists as in python 2 in order to save memory. Some of them zip()

filter()

map()

including. keys .values .items()

dictionary methods But duplicate objects are ineffective if you are trying to iterate multiple times to use a method list()

to convert them to lists

0


source


In python3, do

A = range(0,6)
A = list(A)
print(A)

      

You will get the same result.

-2


source







All Articles