This post will discuss how to retrieve elements from a set in Python.

Sets are non-linear unordered data structures. That means you can’t retrieve an item in a set using the index as you used to do with lists. However, you can retrieve all elements or an arbitrary element from a set without an explicit index.

1. Retrieve an arbitrary element from a Set

To retrieve an arbitrary item from the set, a simple solution is to convert the set into a list and then call its pop() function.

Download  Run Code

 
The problem with the above approach is that it creates a new list. This is unnecessary for getting a single element from the set and is very expensive for large sets.

An efficient option is to create an iterator object and get the first item from the iterator using the next() function.

Download  Run Code

2. Retrieve all elements from a Set

To retrieve all elements from a set, you can use a simple for-loop.

Download  Run Code

 
Another approach is to create an iterator object and retrieve the items from it using the next() function. The next() function raises StopIteration when the iterator is exhausted.

Download  Run Code

 
You can also supply a default value to the next() function. Now when the iterator is exhausted, the default value is returned instead of raising StopIteration.

Download  Run Code

That’s all about retrieving elements from a set in Python.