I'm studying Python basics, but I don't understand something

Asked 2 years ago, Updated 2 years ago, 13 views

'''

a=[1,2,3]

import copy

b=copy.copy(a)

a==b and a is b

?

'''

It's a question to find the answer I don't understand why a is b is false.

They both come out [1,2,3] the same

python

2022-09-22 13:30

1 Answers

== compares the values and is compares the addresses.

The a and b variables contain lists of 1, 2, and 3 integers.

The value that the variable implies is the same. But are the two variables holding the same memory address?

copy.copy works to copy the new memory address to have the same value. Therefore, a and b store lists at different memory addresses.

import copy
a = [1, 2, 3]
b = copy.copy(a)

print(id(a))
print(id(b))

If you run the above code, you can see that the address is different between a and b displayed on the screen.

The result is False because is compares the addresses to determine if they are the same instance.


2022-09-22 13:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.