Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python range( ) is not giving me a list [duplicate]

Tags:

python

range

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!

like image 465
R14 Avatar asked Oct 09 '13 09:10

R14


1 Answers

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.

like image 103
TerryA Avatar answered Nov 07 '22 15:11

TerryA