Access the sole element of a set

Viewed 39836

I have a set in Python from which I am removing elements one by one based on a condition. When the set is left with just 1 element, I need to return that element. How do I access this element from the set?

A simplified example:

S = set(range(5))
for i in range(4):
    S = S - {i}
# now S has only 1 element: 4
return ? # how should I access this element
# a lame way is the following
# for e in S:
#    return S
6 Answers

One way is: value=min(set(['a','b','c')) produces 'a'. Obviously you can use max instead.

  1. A set is an unordered collection with no duplicate elements.

  2. Basic uses include membership testing and eliminating duplicate entries.

  3. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

  4. to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

  5. sort a set in acceding/Descending order -> Returns a List of sorted elements, doesn't change the set

    sorted(basket) # In Ascending Order sorted(basket, reverse=True) # In descending order

To get x element of set or from sorted set

list(basket)[x] or sorted(basket)[x] 

Note: set is unordered set, so you can use the below code to get x element from a sorted set

Related