How to fill a list

后端 未结 5 568
深忆病人
深忆病人 2021-01-05 03:26

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]
         


        
5条回答
  •  天命终不由人
    2021-01-05 04:01

    • 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.

提交回复
热议问题