Justin Nguyen
Justin Nguyen

Reputation: 1

Why are the id's different when they both print out the same value?

I have two sets of code in python

one_set = set()
one_set.add("a")
two_set = one_set

print(id(one_set))
print(id(two_set))

After this code is printed, the id's appear to be the same

oneset = set()
oneset.add("a")
twoset = oneset.copy()

print(id(oneset))
print(id(twoset))

but when this code is printed, when you print out both of their id's, it is different. Why does the first set of code have the same id's and the second set have different id's, even though they both print the same value "a".

Upvotes: 0

Views: 121

Answers (2)

0xRyN
0xRyN

Reputation: 872

Each object in Python has it's unique id.

When you do

two_set = one_set

You're not creating a new object. You're telling python to give another name to the same object, a reference.

To prove that, if you do

two_set.add("b")

and print one_set, one_set will have "a" and "b" as values.

However, when you use a copy() function, python will create a new object, copy the old object's values into the new object.

and if you do

two_set.add("b")

it won't affect one_set.

one_set and two_set are now completely independant objects.

Upvotes: 1

Palinuro
Palinuro

Reputation: 348

The answer is "aliasing". In your first code, when you do:

two_set = one_set

you are calling one_set with another name: two_set. So, if both are the same object, the id will be the same.

In the second case, you copy the object. Then, one_set and two_set will be different objects, having different id value (that is, a different memory address).

Upvotes: 2

Related Questions