Pass a list of variables to a procedure
Keith Burns
alagalah at gmail.com
Sat Apr 7 20:16:12 EDT 2012
Thank you, Chris!
Sent from my iPhone
On Apr 7, 2012, at 3:24 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> On Sat, Apr 7, 2012 at 2:15 PM, KRB <alagalah at gmail.com> wrote:
>> Hi there,
>>
>> I would like to be able to pass a list of variables to a procedure, and have the output assigned to them.
>
> You cannot pass a variable itself to a function; you can only pass a
> variable's value. Which is to say that Python doesn't use
> pass-by-reference.
> Without using black magic, a Python function cannot rebind variables
> in its caller's scope. Mutable values can be mutated however.
> Details: http://effbot.org/zone/call-by-object.htm
>
>> For instance:
>>
>> x=0
>> y=0
>> z=0
>>
>> vars =[x,y,z]
>> parameters=[1,2,3]
>>
>> for i in range(1,len(vars)):
>> *** somefunction that takes the parameter "1", does a computation and assigns the output to "x", and so on and so forth.
>>
>> Such that later in the program I can
>> print x,y,z
>>
>> I hope that makes sense, otherwise I have to do:
>> x=somefunction(1)
>> y=somefunction(2)
>> z=somefunction(3)
>> etc etc
>
> Just use sequence (un)packing:
>
> def somefunction(*parameters):
> # one would normally use a list comprehension here;
> # for simplicity, I'm not
> results = []
> for parameter in parameters:
> result = do_some_calculation(parameter)
> results.append(result)
> return results
>
> #…later...
> x, y, z = somefunction(1, 2, 3)
>
>
> Relevant docs:
> http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences
> http://docs.python.org/tutorial/controlflow.html#tut-unpacking-arguments
>
> Cheers,
> Chris
More information about the Python-list
mailing list