7

Having a beginner issue with Python range.

I am trying to generate a list, but when I enter:

def RangeTest(n):

    #

    list = range(n)
    return list

print(RangeTest(4))

what is printing is range(0,4) rather than [0,1,2,3]

What am I missing?

Thanks in advance!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
R14
  • 152
  • 1
  • 10

1 Answers1

18

You're using Python 3, where range() returns an "immutable sequence type" instead of a list object (Python 2).

You'll want to do:

def RangeTest(n):
    return list(range(n))

If you're used to Python 2, then range() is equivalent to xrange() in Python 2.


By the way, don't override the list built-in type. This will prevent you from even using list() as I have shown in my answer.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • Aah, and just realised that list is built-in... – R14 Oct 09 '13 at 09:46
  • @Haidro, `This will prevent you from even using list() as I have shown in my answer.` - the `list` type is still available as `__builtins__.list`. – Maciej Gol Oct 09 '13 at 10:07
  • @kroolik Well yea, :p. or also doing `del list` – TerryA Oct 09 '13 at 10:12
  • you means for Python >= 3 `range` is `xrange` and original `range` no more exists? – Grijesh Chauhan Oct 10 '13 at 04:06
  • @Haidro Recently I read [this answer](http://stackoverflow.com/questions/19278084/zip-function-giving-incorrect-output-in-python/19278108#19278108) about zip and I notice in new versions of Python all in-build function returns iterator instead of sequences. Is my observation is correct? – Grijesh Chauhan Oct 10 '13 at 04:22
  • 1
    @GrijeshChauhan Yes. `zip()`, `map()` and `filter()` all return iterators in python 3. You can do this in python 2 using the `itertools` module. I'd link you, but I'm on my phone, sorry – TerryA Oct 10 '13 at 04:27