-1

I am learning Python3 and as I can see in the past, with Python2, it was possible to create a list of numbers with range() by just passing a single argument, which would be the last number of list + 1 in the list:

range(4) # == [0, 1, 2, 3]

and the start and step values were defaulted to 0 and 1.

But in Python3 for some reason, it is no longer possible to omit those 2 arguments and for the same result we would need to wrap the range() function with the list() function:

range(0, 4, 1) # == range(0, 4)
range(4) # == range(0, 4)
list(range(4)) # == [0, 1, 2, 3]

Question(s):
What is the reason behind that? Why was the functionality changed this way? Is there a good reason for that?

P.S. or maybe I am doing something incorrectly. Here, I am talking about range() function in general, whether it is being used in for-loops, just to create a list or for any other purpose

Eduard
  • 8,437
  • 10
  • 42
  • 64
  • 2
    It's nothing to do with which arguments you omit. `range(0,4,1)` and `range(4)` are still equivalent; they just don't produce a list any more. – khelwood Dec 19 '17 at 14:31
  • 1
    The difference of `range` between P2 and P3 is well documented. What specifically is unclear? `range` in P3, as much as `xrange` in P2 takes the same arguments as P2 `range`. They just don't return a `list`. – too honest for this site Dec 19 '17 at 16:18

1 Answers1

1

You've unfortunately been misled by the repr of range:

>>> range(4)
range(0, 4)

It is actually the same interface, but this is returning a lazily-generated sequence now, as opposed to a list. You may iterate a range instance to consume the values:

>>> list(range(4))
[0, 1, 2, 3]

See Python range() and zip() object type for more details about this change.

wim
  • 338,267
  • 99
  • 616
  • 750