Ask Your Question
1

Adding elements to a set

asked 2019-06-04 20:58:51 +0100

updated 2019-08-29 18:55:16 +0100

FrédéricC gravatar image

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])
D.add(c)

gives the error

'Set_object_enumerated_with_category' object has no attribute 'add'

whereas

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

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 flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2019-06-04 21:13:51 +0100

rburing gravatar image

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.

edit flag offensive delete link more

Comments

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.

Jesus Martinez Garcia gravatar imageJesus Martinez Garcia ( 2019-06-05 01:51:32 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2019-06-04 20:58:51 +0100

Seen: 2,542 times

Last updated: Jun 04 '19