Question

explain the difference between mutating a value and rebinding a variable and give an example of...

explain the difference between mutating a value and rebinding a variable and give an example of code that might trip up someone who doesn't get the difference, and explain why it might trip them up.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Mutating a value and Rebinding a variable are two important concepts and if not used correctly can create logical errors.

In Python, a variable is called a name.

Let's first understand binding & rebinding:

x = 1
(Here value 1 is bound to name x)


y = 2
(Here value 2 is bound to name y)


z = x
(Here the value of x is bound to name z, means 1 is bound to z)

Note: Python didn’t create or copy the object 1, it only assigned a new name for that value/object. So both x and z are bound to the object 1.

Let's see State:
x ---> 1 <--- z
y ---> 2

what if, we do x = y

This will not create any new value/object this will only rebind name x with the value of y.
New State,

1 <--- z
y ---> 2 <--- x

So, this was binding and rebinding.


Now, Let's understand Mutating

Let,
a = [1, 2]
This will bind object [1, 2] with name 1


Now,
b = a
This will similar to the previous case will bind object [1, 2] with name b

So State,
a ---> [1, 2] <--- b

Now both names are pointing to the same value, what if we append new data

a.append(3)

We not creating any new value and only changing the existing value.
This will change value/object and both names a and b are pointing to the same object to so they will show newly updated results

State:
a ---> [1, 2, 3] <--- b

if we print b, it will show [1, 2, 3]

And who doesn't understand the difference will think that b is still [1, 2], And will use accordingly and create errors.

If we wanted to a to be [1, 2, 3] and b to be [1, 2] then instead of appending or mutating we could have rebound a with a new object, like

a = [1, 2, 3]

Then States would have

[1, 2] <--- b
a ---> [1, 2, 3]

Code: (Text file also included in End)

Code:

# Mutating
print("Mutating")
a = [1, 2]
b = a
a.append(3)
print("a:", a)
print("b:", b)

# Rebinding
print("\nRebinding")
c = [1, 2]
d = c
c = [1, 2, 3]
print("c:", c)
print("d:", d)

PLEASE UPVOTE.THANKYOU...!!

Add a comment
Know the answer?
Add Answer to:
explain the difference between mutating a value and rebinding a variable and give an example of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT