# Adding elements to a set I learned Python a long while ago before I decided to get into SageMath for mathematical purposes.

I am a bit puzzled that I don't seem to have a way to add an element to a set when using the SageMath definition 'Set()', but there seems to be no problem when doing this using the Python definition 'set()', namely:

a=2; b=3; c=4
D=Set([a,b])


gives the error

'Set_object_enumerated_with_category' object has no attribute 'add'


whereas

a=2; b=3; c=4
D=set([a,b])


gives no problem (notice the difference in capital letter when creating set).

I am using the following workaround

a=2; b=3; c=4
D=Set([a,b])
D=D.union(Set([c]))


but it seems rather artificial. Is there no more natural way to proceed? Is there a natural reason to explain why 'add' is not a method of 'Set'?

edit retag close merge delete

Sort by » oldest newest most voted The documentation on sets explains it well:

If X is a list, tuple, Python set, or X.is_finite() is True, this returns a wrapper around Python’s enumerated immutable frozenset type with extra functionality. Otherwise it returns a more formal wrapper.

If you need the functionality of mutable sets, use Python’s builtin set type.

So Set([a,b]) acts more like Python's frozenset (hence it has no method to add an element).

If you want a mutable set, just use Python's set type.

more

1

Thank you. Incidentally, I think that suggest an answer for my last question ('Is there a natural reason to explain why 'add' is not a method of 'Set'?'): if one wants a mathematical notion of set, we want to be able to create 'set of sets' naturally. Now I remember having this problem in Python when dealing with sets of sets: because the set is mutable (and hence not hashable), one has to create a frozen set, and then a set of frozen sets. From that point of view the Sage design is more natural.