Reputation: 21
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
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
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:
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