Paul Ahuevo
Paul Ahuevo

Reputation: 131

Python3 - use function parameter as name of variable

I have a function that creates different forms of arrays and I don't know how to differentiate them. Is something similar to this possible?

def array_creator(nameArray):
    nameArray = [0,1,2]

array_creator(a)
print(a)  # prints [0,1,2]

At the moment I always run the function and then assign manually variables to store the arrays. Thanks!

Upvotes: 0

Views: 278

Answers (3)

Bakuriu
Bakuriu

Reputation: 101959

Python does not have "output parameters", hence a plain assignment will only change the binding of the local variable, but will not modify any value, nor change bindings of variables outside the function.

However lists are mutable, so if you want to modify the argument just do so:

nameArray[:] = [0,1,2]

This will replace the contents of nameArray with 0,1,2 (works if nameArray is a list).

An alternative is to have your function simply return the value you want to assign:

def array_creator():
    values = [0, 1, 2]
    return values

my_arr = array_creator()

Finally, if the function wants to modify a global/nonlocal variable you have to declare it as such:

a = [1,2,3]

def array_creator():
    global a
    a = [0,1,2]

print(a)   # [1,2,3]
array_creator()
print(a)   # [0,1,2]

Or:

def wrapper():
    a = [1,2,3]
    def array_creator():
        nonlocal a
        a = [0,1,2]
    return a, array_creator

a, creator = wrapper()

print(a)   # [1,2,3]
creator()
print(a)   # [0,1,2]

Note however that it is generally bad practice to use global variables in this way, so try to avoid it.

Upvotes: 0

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

In Python you do this by returning a value from the function and binding this value to a local name, ie:

def array_creator():
    return [0, 1, 2]

a = array_creator()

Upvotes: 1

MrLeeh
MrLeeh

Reputation: 5589

For your example to work you need to define your variable a before you use it. E.g. a = []. However your example won't work the way you want to. The reason for this is that you assign a new object ([1, 2, 3]) to your nameArray variable in line 2. This way you lose the reference to your object a. However it is possible to change your object a from inside the function.

def array_creator(nameArray):
    nameArray.extend([0,1,2])

a = []
array_creator(a)
print(a)  # prints [0,1,2]

This will work. Have a look at How to write functions with output parameters for further information.

Upvotes: 1

Related Questions