Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a list of parameters into a Python function [duplicate]

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

like image 713
knw500 Avatar asked Apr 01 '15 20:04

knw500


People also ask

How do you pass a copy of a list to a function in Python?

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.

Can you pass a list as a parameter in Python?

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.

Does Python pass by reference or copy?

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.

How do you pass a list by reference in Python?

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.


2 Answers

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.

like image 137
frnhr Avatar answered Oct 17 '22 06:10

frnhr


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

like image 33
Bhargav Rao Avatar answered Oct 17 '22 05:10

Bhargav Rao