4

In Python 2.7 if run the following line of code:

print(range(0, 20))

It returns:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

but in 3.4 it returns:

range(0, 20)

I know there are differences between the two versions, I just don't know what they are in this case. Could somebody answer these two questions,

  1. What is going on to make them different?
  2. How can I make 3.4 return the list and how can I get 2.7 to return the statement if I wanted it to?
vaultah
  • 44,105
  • 12
  • 114
  • 143
jackjameshoward
  • 167
  • 1
  • 7

2 Answers2

3

Python 2 and 3 are a bit different.

Range will not do what you are asking for in the version 3. As another example, in python3, xrange is no longer used.

Getting back to your question, do the following in Python3

ab = list(range(20))

Again, google is your friend... ;)

And find the major difference between python2 and python3, here

PS: One gent here nicely advised me to use Python3 instead of Python2 as Py2 will be deprecated in 2020. Thinking about it, long time but not that long actually.

Andy K
  • 4,944
  • 10
  • 53
  • 82
2

range now is an iterator and it's returns his values when you iterate over it, one after the other.

If you would like to get whole list you have to call list:

list(range(0, 20))

But in most cases more better use range as is without list(range(...)), because it saves in memory. In turn, range in the second version immediately creates the entire list, also in second python there is special xrange that return iterator like in third.

For more details, please click here

Andy K
  • 4,944
  • 10
  • 53
  • 82
Peter
  • 1,223
  • 3
  • 11
  • 22