Retrieve elements from a Python set
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = {1, 2, 3, 4, 5} x = list(s).pop() print(x) # 5 |
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = {1, 2, 3, 4, 5} x = next(iter(s)) print(x) # 1 |
2. Retrieve all elements from a Set
To retrieve all elements from a set, you can use a simple for-loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
if __name__ == '__main__': s = {1, 2, 3, 4, 5} for x in s: print(x) ''' Output: 1 2 3 4 5 ''' |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if __name__ == '__main__': s = {1, 2, 3, 4, 5} it = iter(s) while True: try: x = next(it) except StopIteration: break else: print(x, end=' ') # 1 2 3 4 5 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = {1, 2, 3, 4, 5} it = iter(s) while True: x = next(it, None) if not x: break print(x, end=' ') # 1 2 3 4 5 |
That’s all about retrieving elements from a set in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)