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

牧云@^-^@ 提交于 2019-12-19 07:50:26

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/19268352/python-range-is-not-giving-me-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!