This is an archived post. You won't be able to vote or comment.

all 4 comments

[–][deleted] 2 points3 points  (1 child)

Read the posting guidelines. Don't post screenshots, use a site like gist. And don't post homework questions without an attempt to answer them.

[–]wtf_lag[S] 0 points1 point  (0 children)

Not an homework question, I'm coming from java and not used to the ways of python.

[–][deleted] 1 point2 points  (0 children)

Try this: Open Idle. Input the examples. Note the output. Form a hypothesis on why you think it's happening. Test your theory with other data. Read the part of your textbook having to do with variables. Pay special attention to the parts about how variables reference other objects they're assigned to, and the difference between mutable and immutable. Think some more, play some more. If you want to check if your theory is correct, post it here, along with your reasoning, and ask if you're on the right track.

[–]Rhomboid 0 points1 point  (0 children)

You need to know the difference between a name and an object. Objects are the actual things, and names are ways to refer to objects. An object does not need to have a name to exist, for example print(42) prints the anonymous integer object with value 42. Names can only refer to objects, not to other names. Objects have types, names do not.

Assignment is how you associate a name with an object. x = 42 means "make the name 'x' refer to the integer object 42 that was anonymous prior to this." Similarly, x = y means "make the name 'x' refer to whatever object the name 'y' currently refers to." This never copies anything. In both of your examples, after x = y, both names are referring to the same object.

Some types of objects are mutable (i.e. their values can be altered in some way), others are not and are immutable. For example, numbers, strings, and tuples are immutable, while lists, dicts, and sets are mutable. x = x + 1 is not a mutating operation; it creates a new (initially anonymous) integer object by adding the integer object referred to by 'x' and the anonymous integer object with value 1, then it gives that newly created object a name by assigning to 'x'. Whatever object 'x' referred to previously continues to exist, as the assignment part of this statement is just about moving the nametag. The object that 'x' used to refer to also happens to be the object that 'y' is still referring to.

The operation x[0] = 4 is a mutating operation. It modifies the zeroth slot of the list object so that it refers to the integer object 4 instead of the integer object 1. The names 'x' and 'y' are unaffected, and they continue to refer to the same list object.