Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill a list

Tags:

python

list

fill

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.

like image 744
Linus Svendsson Avatar asked Dec 08 '11 10:12

Linus Svendsson


3 Answers

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)
like image 133
tito Avatar answered Nov 15 '22 18:11

tito


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

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

print(l)
like image 22
user5214530 Avatar answered Nov 15 '22 19:11

user5214530


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)
like image 26
Fred Foo Avatar answered Nov 15 '22 19:11

Fred Foo