Skip to content

Conversation

@davidherbert2
Copy link

Have added hopefully clarifying examples to the section on variable assignment, drawing attention to the issue raised in #370 that the statement in the section title is not true in all cases. Refers to the example in episode 11 to put the issue in a list context.

Copy link
Member

@alee alee left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! I think this is an important improvement to the lesson and clarifies things nicely. However, (and apologies for the pedantry), b is not really a copy of a. It's being assigned to the value of a, which is the canonical int object 1. You can't mutate / modify an int object, or a string object, or a tuple object - they are guaranteed to be immutable.

You can test this by using the id function, e.g.,

a = 396
b = 242
id(a)
id(b)
b = a
id(b)
id(396)

You'll see that id(b) reports the same unique id that a has, and the same as id(396).

However, if you assigned a to a mutable object like a list, map, set, or a custom class that holds some variable references to other value objects (e.g., numbers, strings, tuples), you could dig into that mutable object and change one of those internal references to point at a different value object, which is what you refer to later with the spreadsheet analogy.

IIRC Python is a call-by-object-reference language - everything is an object, and what really matters is whether you assign a mutable object or an immutable object to a variable name. If you assigned a mutable object, then you have the ability to change any of its mutable references, e.g.,

a = [3, 4, 5]
b = a
b.append(6)
# a is now [3, 4, 5, 6]

However, something like:

a = [3]
b = a
b = [4]

does not change a for example.

Would you be willing to revise this PR to include some of this nuance? I'd be happy to help edit the PR myself but don't have much bandwidth until the end of this month or the beginning of November likely...

Thanks again for taking the time to help us improve this lesson!

@hangyiatwsu
Copy link

Agreed with alee's comments that b is not really a copy of a, it should be assigned to the current value of a. #370 #396 #499
a = [1, 2, 3]
b = a
print(a)
print(b)
a[2] = 4
print(a)
print(b) # assigning current value of a to b

@alee
Copy link
Member

alee commented Apr 19, 2023

Closing this PR in preparation for a Carpentries-wide lesson infrastructure upgrade. Please feel free to resubmit or we can continue to gather community input on this suggestion in #370

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants