How to fill a list

主宰稳场 提交于 2019-11-30 03:30:43

问题


I have to make a function that takes an empty list as first argument and n as secound argument, so that:

L=[]
function(L,5)
print L
returns:
[1,2,3,4,5]

I was thinking:

def fillList(listToFill,n):
    listToFill=range(1,n+1)

but it is returning an empty list.


回答1:


Consider the usage of extend:

>>> l = []
>>> l.extend(range(1, 6))
>>> print l
[1, 2, 3, 4, 5]
>>> l.extend(range(1, 6))
>>> print l
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

If you want to make a function (doing the same):

def fillmylist(l, n):
    l.extend(range(1, n + 1))
l = []
fillmylist(l, 5)



回答2:


A function without an explicit return or yield returns None. What you want is

def fill_list(l, n):
    for i in xrange(1, n+1):
        l.append(i)
    return l

but that's very unpythonic. You'd better just call range(1, n+1) which also returns the list [1,2,3,4,5] for n=5:

def fill_list(n):
    return range(1, n+1)



回答3:


In

def fillList(listToFill,n):
    listToFill=range(1,n+1)

you change only the pointer of listToFill, if you don't return the new pointer; the new pointer isn't available out of the function and you have still the pointer of your empty list (in outer scope).




回答4:


  • If you do :

def fillList(listToFill,n): listToFill=range(1,n+1)

a new list is created inside the function scope and disappears when the function ends. useless.

  • With :

def fillList(listToFill,n): listToFill=range(1,n+1) return listToFill()

you return the list and you must use it like this:

newList=fillList(oldList,1000)
  • And finally without returning arguments:

def fillList(listToFill,n): listToFill.extend(range(1,n+1))

and call it like this:

fillList(oldList,1000)

Conclusion:

Inside a function , if you want to modify an argument you can reassign it and return it, or you can call the object's methods and return nothing. You cannot just reassign it like if you were outside of the function and return nothing, because it's not going to have effect outside the function.




回答5:


And a bit shorter example of what you want to do:

l = []
l.extend(range(1, 5))
l.extend([0]*3)

print(l)


来源:https://stackoverflow.com/questions/8429794/how-to-fill-a-list

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