0

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!

2
  • 1
    but why not just do a = [0, 1, 2]? Why confuse people by assigning to the global scope from inside a function? Commented Dec 19, 2016 at 10:47
  • 3
    Why not just return the array, instead of using an "output-parameter"? Commented Dec 19, 2016 at 10:59

3 Answers 3

1

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.