How to fill a list

后端 未结 5 535
深忆病人
深忆病人 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 03:45

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

    0 讨论(0)
  • 2021-01-05 03:49

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

    l = []
    l.extend(range(1, 5))
    l.extend([0]*3)
    
    print(l)
    
    0 讨论(0)
  • 2021-01-05 03:54

    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)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-05 04:02

    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)
    
    0 讨论(0)
提交回复
热议问题