Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

list - Python 3 range Vs Python 2 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...