+ 2

Set in python are mutable or immutable

26th Jan 2024, 1:44 PM
Ahsan khan
Ahsan khan - avatar
4 ответов
+ 4
""" Codewithdark , The best source is always python.org. https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset But it's actually a tricky question if you try to answer it yourself. Normally, to test if an object is immutable, you modify it and see if its id() changes. If the id() changes, it's immutable. If it stays the same, it's mutable. However, depending how you modify a set, you can find the id() changing or staying the same. """ p = print s = {5} p(s) # {5} p(id(s)) # note the number p() s = s | {6} p(s) # {5, 6} (or {6, 5}) p(id(s)) # id changes, implying immutable p() s.add("z") p(s) # {5, 6, 'z'} (or some other order) p(id(s)) # id doesn't change, implying mutable p() """ To resolve that, realize that mutable trumps immutable. If there exists a way to modify an object without changing its id(), it must be mutable, no matter that there are also ways to modify it and change the id(). Bottom line, set is mutable, as the docs say. """
26th Jan 2024, 4:46 PM
Rain
Rain - avatar
+ 2
try to change a set by adding or removing an element. observe.
26th Jan 2024, 2:17 PM
Lisa
Lisa - avatar
+ 2
Codewithdark , I don't remember where I first read this little gem about sets. It's not mine, but I like it. Maybe you will too. "Unordered doesn't mean guaranteed not to have an order. It means not guaranteed to have an order."
27th Jan 2024, 12:28 AM
Rain
Rain - avatar
+ 1
immutable
27th Jan 2024, 6:04 AM
S8ul Yuvraj
S8ul Yuvraj - avatar