35

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?

2
  • 1
    In Python-3.x, range(..) no longer produces a list, it produces a range object, that allows iteration, but also fast len(..), in checks, etc. Commented Jun 15, 2017 at 15:43
  • See this question and its answers. Commented Oct 10, 2017 at 10:40

4 Answers 4

35

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))
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

2

Python 3 range() function is equivalent to python 2 xrange() function not range()

Explanation

In python 3 most function return Iterable objects not lists as in python 2 in order to save memory. Some of those are zip() filter() map() including .keys .values .items() dictionary methods But iterable objects are not efficient if your trying to iterate several times so you can still use list() method to convert them to lists

Comments

1

In python3, do

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

You will get the same result.

1 Comment

The question asks a lot more than how to get the python2 behavior

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.