How to fill a list

后端 未结 5 534
深忆病人
深忆病人 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: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)
    

提交回复
热议问题