Winters89
Winters89

Reputation: 21

simple python function tracing

I am quite new to python and am attempting to trace this simple program. I want to improve my ability to look at code and understand what the output will be.

To be honest I am just starting to study for a intro python final exam and am having trouble in the course. If anyone knows of any good concise resources on intro python they've used in the past that would be of great help as well.

Here is the program.

def fun(x):
    x[0] = 0
    x = [4,5,6]
    return x

def main():
    y = [1,2,3]
    z = fun(y)
    print("z =",z)
    print("y =",y)

main()

so basically I want someone to explain why the output is this:

z = [4, 5, 6]
y = [0, 2, 3] 

Upvotes: 1

Views: 102

Answers (2)

martineau
martineau

Reputation: 123453

Here's an example of something simple you could add to trace the execution of your code:

import sys

def tracer(frame, event, arg):
    print(event, frame.f_lineno, frame.f_locals)
    return tracer

sys.settrace(tracer)

def fun(x):
    x[0] = 0
    x = [4,5,6]
    return x

def main():
    y = [1,2,3]
    z = fun(y)
    print("z =",z)
    print("y =",y)

main()

Upvotes: 1

David Reeve
David Reeve

Reputation: 871

Think of assignment of lists and objects in Python more like binding. y doesn't refer to [1,2,3], but it's bound to it. Other variables assigned to y are also bound to the list object.

Therefore, the process your code steps through is as follows:

  1. Create a list [1,2,3] and assign its location to variable y.
  2. Pass y to fun as x. x refers to the location of the list [1,2,3].
  3. Set x[0], which refers to [1,2,3][0], to 0. Therefore, [1,2,3] becomes [0,2,3].
  4. Set x to the list [4,5,6]. x no longer refers to [0,2,3], but instead to [4,5,6], a new list object.
  5. Pass x back to variable z. z now refers to the location of [4,5,6].

If you don't want to modify a list or object in another function, you can use the copy() and deepcopy() methods to create new objects. i.e.

fun( y )            # passes [1,2,3] into fun()
fun( y.copy() )     # passes a copy of [1,2,3] into fun()

Upvotes: 0

Related Questions