How to fill in the list

I need to make a function that takes an empty list as the first argument, and n is the sound argument, so:

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

I thought:

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

but it returns an empty list.

+8
source share
5 answers

Consider using 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 (do the same):

 def fillmylist(l, n): l.extend(range(1, n + 1)) l = [] fillmylist(l, 5) 
+17
source

A function without an explicit return or yield returns None . Do you want to

 def fill_list(l, n): for i in xrange(1, n+1): l.append(i) return l 

but it is very messy. You better just call range(1, n+1) , which also returns a list [1,2,3,4,5] for n=5 :

 def fill_list(n): return range(1, n+1) 
+4
source

IN

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

you only change the listToFill pointer if you do not return a new pointer; the new pointer is not accessible from the function, and you have a pointer to an empty list (in the outer scope).

0
source
  • If you do:

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

a new list is created inside the scope and disappears when the function ends. useless.

  • FROM:

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

you will return the list and you should use it like this:

 newList=fillList(oldList,1000) 
  • And finally, without returning arguments:

def fillList(listToFill,n): listToFill.extend(range(1,n+1))

and name it as follows:

 fillList(oldList,1000) 

Conclusion

Inside a function, if you want to change an argument, you can reassign it and return it, or you can call the methods of the object and not return anything. You cannot just reassign it as if you were outside the function and did not return anything, because it will not have an effect outside the function.

0
source

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

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

Source: https://habr.com/ru/post/903365/


All Articles