Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 range Vs Python 2 range

Tags:

python

list

range

I recently started learning python 3.
In python 2 the range() function can be used to assign list elements:

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

But in python 3 the range() function outputs this:

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

Why is this happening?
Why did python do this change?
Is it a boon or a bane?

like image 207
Hari Narayana Batta Avatar asked Jun 15 '17 15:06

Hari Narayana Batta


People also ask

Is there a big difference between Python 2 and 3?

Python 3 is definitely more readable, easier to grasp, and popular than Python 2. Python 2 has definitely run out of steam and one should learn Python 2 if and only if some legacy code has been written in Python 2 or if a company needs the developer to migrate the Python 2 code into Python 3.

Which is faster Python 2 or 3?

Python 3.3 comes faster than Python 2.7.

How does range work in Python 3?

Python range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.


1 Answers

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)) 
like image 55
Sam Hartman Avatar answered Oct 02 '22 00:10

Sam Hartman