how would I pass an unknown number of parameters into a function? I have a function defined in the following way
def func(x, *p):
return ...
I'm trying to pass in a list of values to use as parameters. I tried using a list and a tuple but the function always returns zero. Has anyone got any advice? Thanks
You can use [:] , but for list containing lists(or other mutable objects) you should go for copy. deepcopy() : lis[:] is equivalent to list(lis) or copy. copy(lis) , and returns a shallow copy of the list.
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
What is Pass by Reference In Python? Pass by reference means that you have to pass the function(reference) to a variable which refers that the variable already exists in memory. Here, the variable( the bucket) is passed into the function directly.
some_list = ["some", "values", "in", "a", "list", ]
func(*some_list)
This is equivalent to:
func("some", "values", "in", "a", "list")
The fixed x
param might warrant a thought:
func(5, *some_list)
... is equivalent to:
func(5, "some", "values", "in", "a", "list")
If you don't specify value for x
(5
in the example above), then first value of some_list
will get passed to func
as x
param.
Pass the values as comma separated values
>>> def func(x, *p): # p is stored as tuple
... print "x =",x
... for i in p:
... print i
... return p
...
>>> print func(1,2,3,4) # x value 1, p takes the rest
x = 1
2
3
4
(2,3,4) # returns p as a tuple
You can learn more by reading the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With