Reputation: 173
How can I delete the last element of a set, or create a new set without last element? Sets do not support indexing. I have a set of integers, and want to remove the largest.
Upvotes: 2
Views: 13192
Reputation: 77850
You can remove any specified element with the remove
method:
>>> s = {3, 'a', True}
>>> s
{'a', True, 3}
>>> s.remove(3)
>>> s
{'a', True}
However, any concept of "last" must come from beyond the set itself, since a set does not implement the idea of a fixed order. Note the difference above between the assigned value and the printed value.
Update after OP clarification
To remove the numerically largest element of the set:
s.remove(max(s))
You commented:
if a set contains only integers, then the elements are by default listed in ascending order.
This is incorrect. For example:
>>> lll = [3**n for n in range(10)]
>>> sss = set(lll)
>>> sss
{1, 6561, 3, 19683, 9, 2187, 81, 243, 729, 27}
Perhaps you're confused by some of the effects of small integers in Python. The integer constants up to (usually) 256 are pre-allocated by the run-time system, stored in numerical order in memory, with special hash handling. One effect of this is that their hash values are in order. Once you go beyond that range, the hashing is different, as seen above:
Upvotes: 5
Reputation: 1784
As everyone here has said, sets are unordered, but if you want to remove an element from the set you could do the following (let's call the set a_set):
a_set = set(list(a_set)[:-1])
I want to make it clear- you're not removing the last element of the set, because there is no such thing, but you're converting it to a list, removing the last element, then converting back
Upvotes: 0
Reputation: 204
The sets are unordered collections. Refer to https://docs.python.org/3/tutorial/datastructures.html#sets. Try using List instead to do what you intended. Then variable.pop(0) method will do the job.
Upvotes: 0
Reputation: 14104
I don't think you can do that since there is no last element
of a set. As you can see from the documentation https://docs.python.org/2/library/sets.html, sets are unordered.
Upvotes: 0