How to fill a list

Linus Svendsson picture Linus Svendsson · Dec 8, 2011 · Viewed 52.1k times · Source

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.

Answer

tito picture tito · Dec 8, 2011

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)