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, 2019 in Python by ana1504.k
• 7,910 points
622 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, 2019 by SDeb
• 13,300 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 aryya
• 7,460 points
1,497 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
• 58,020 points
845 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
• 58,020 points
874 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
1,067 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
1 answer

How to Reverse a list in Python

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

answered Sep 29, 2018 in Python by SDeb
• 13,300 points
843 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,300 points
921 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP