How to fill a list?

0 votes

I have to make a function that takes an empty list as first argument and n as a secound argument, so that:

L=[]
function(L,5)
print L
returns:
[1,2,3,4,5]

I tried the following:

def fillList(listToFill,n):
    listToFill=range(1,n+1)

but it is returning an empty list. Can anyone help me with this?

Jun 14 in Python by ana1504.k
• 7,870 points
22 views

1 answer to this question.

0 votes

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)
answered Jun 14 by SDeb
• 13,180 points

Related Questions In Python

0 votes
1 answer

How to sort a list of strings?

Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,340 points
49 views
0 votes
1 answer

How to sort a list of strings?

Try  items = ["live", "like", "code", "cool", "bug"] ...READ MORE

answered Jul 27, 2018 in Python by Priyaj
• 56,920 points
30 views
0 votes
1 answer

How to split a string into a list?

You can use the function  text.split() This should be ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 56,920 points
65 views
0 votes
1 answer

How to Print a List in Python

ou are using Python 2.x syntax with ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
95 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 337 views
0 votes
1 answer

How to Reverse a list in Python

You can use the reversed function in ...READ MORE

answered Sep 28, 2018 in Python by SDeb
• 13,180 points
78 views
0 votes
1 answer

How to use a global variable in function?

The global variable can be used in ...READ MORE

answered Sep 27, 2018 in Python by SDeb
• 13,180 points
32 views