1

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] 
3
  • What exactly about the code is troubling you? And asking for external resources such as tutorials is explicitly off-topic for Stack Overflow. Commented Dec 6, 2014 at 21:26
  • Reading between the (code) lines, I suspect that this post might be helpful. Commented Dec 6, 2014 at 21:29
  • And take a look at this visualisation of the code you posted; pay close attention as to what happens to the list objects. Commented Dec 6, 2014 at 21:31

2 Answers 2

1

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

Comments

0

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()

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.