nathanesau
nathanesau

Reputation: 1721

Are return types copied in Python?

I am trying to understand how return works in Python and whether a move operation is being used behind the scenes. Consider the following code:

def get_graph(maze): # maze is a 2D bool matrix, with True representing walls
    nrow = len(maze)
    ncol = len(maze[0])
    graph = {}
    for row in range(nrow):
        for col in range(ncol):
            edges = []
            if col - 1 != -1 and maze[row][col-1] is False:
                edges.append((row, col-1))  # left_edge
            if col + 1 != ncol and maze[row][col+1] is False:
                edges.append((row, col+1))  # right_edge
            if row - 1 != - 1 and maze[row-1][col] is False:
                edges.append((row-1, col))  # top_edge
            if row + 1 != nrow and maze[row+1][col] is False:
                edges.append((row+1, col))  # bottom_edge
            graph[(row, col)] = edges
    return graph

Would graph be moved to g in below code? I assume no deep copy is being performed here.

mat=[[False, False, False, False],
       [True, True, False, True],
       [False, False, False, False],
       [False, False, False, False]]

g = get_graph(mat)

Upvotes: 0

Views: 481

Answers (3)

Scott Hunter
Scott Hunter

Reputation: 49848

You seem to be thinking of variables as containers of data, when they are better thought of as references to data, so that the object doesn't get moved so much as a reference to that object gets copied, hopefully making clear why no copy (deep or otherwise) is involved.

Upvotes: 2

orlp
orlp

Reputation: 117741

Python has no concept of memory locations or the 'moving' of data.

It has two concepts: objects and names.

As far as a user of Python is considered, objects live in a magic cloud, automatically delete themselves when no longer necessary and never move.

Names are created by the assignment operator. When I say a = 5, that does not mean that now a 'contains' the object 5 or that it has 'moved to a', it means I simply created a new name a for the object on the right hand side, which is 5.

Similarly, g = f() for arbitrary function f takes whatever object f returned and makes g a name for that object. It does not copy or move anything.

Upvotes: 3

John Coleman
John Coleman

Reputation: 51998

Do an experiment: If you put print(id(graph)) immediately before the return and put print(id(g)) immediately after the assignment, the same id will be printed, showing that it is only a reference which is returned. This returned reference will prevent the graph from being garbage-collected, which is the usual fate of local variables after a function return.

Upvotes: 0

Related Questions