tmj
tmj

Reputation: 1858

Returning lists from function in python

def _pawnHit(state, user, y):
    not_user = _notUser(user)
    hit = 0
    a=[]

    for coordinate in y[1]:
        if(state.whichUserProper(coordinate[0], coordinate[1]) == not_user):
            hit = 1
            a.append(coordinate)

    if(hit==1):
        return [a,True]

    for coordinate in y[0]:
        if(state.whichUserProper(coordinate[0],coordinate[1] == 7)):
            a.append(coordinate)
        else:
            break

    return [a,False]

In C/C++ we cannot return any variable by reference (especially talking about arrays) declared inside a function(its scope ends as the function returns and the variable is destroyed) unless its memory is allocated using new/malloc and then also we return the pointer to the array.

In python as I don't know how the returning of the lists happen. So I don't know whether this will work or not. The list 'a' has been created inside a function. Will it be destroyed once the function's scope ends? If yes, what's a possible way around it?

P.S. I know I can easily return things like these return [i,j,[k,m]] where i,j,k,m are normal variables.

Upvotes: 0

Views: 685

Answers (2)

poke
poke

Reputation: 387527

Yes, obviously this will work. Python does not want to make you worry about memory management. If you returned something, you can and should expect it to be there.

The reason this works is because all Python objects are allocated on the heap (at least in CPython). Unlike C/C++ where local variables get memory on the stack and the stack memory is removed when a function goes out of scope, everything is allocated dynamically. It’s as if everything would be created using malloc etc. On the other hand, the garbage collection makes sure that the memory of all the objects that are no longer needed is freed automatically, so you never need to worry about anything.

And of course, you can easily verify this behaviour by just testing it:

>>> def giveMeAList(n):
        l = list(range(n)) # create a list with n values
        print(id(l)) # print the id of the list object
        return l
>>> x = giveMeAList(100)
47264136
>>> id(x)
47264136
>>> len(x)
100

As you can see the object id is the same, so it’s the same object.

Upvotes: 2

Ilmo Euro
Ilmo Euro

Reputation: 5105

Yes, it will work. Go ahead!

Python is a garbage-collected language; the runtime takes care of memory deallocation, so you don't have to worry about it. As long as a value is needed, it's not destroyed. For more information, see Python Garbage Collection. Excerpt:

Python's memory allocation and deallocation method is automatic. The user does not have to preallocate or deallocate memory by hand as one has to when using dynamic memory allocation in languages such as C or C++. Python uses two strategies for memory allocation reference counting and garbage collection. © Digi International, Inc., www.digi.com

Upvotes: 1

Related Questions