'What is the appropriate way to access data from Python sets?
If a set that always consists of one element (the element is an element of a custom class which contains different data types) is returned by a function, what is the appropriate way to access that element?
At the moment I just use a for
loop to loop through the elements of the set, but since I know that the set will contain only one element there must be a better way to access the data.
So instead of this:
my_set = {'Custom type'}
for i in my_set:
print(i)
What would be the best way to access the element contained in the set. (Please assume that the content of the actual set is a custom type and not a string like in the example given.)
Solution 1:[1]
You can use unpacking:
s = {'item'} # 1-element set
item, = s # unpacking (note the comma)
print(item)
Solution 2:[2]
You can just use .pop()
. It will return an arbitrary item. If it's empty, you'll have KeyError: 'pop from an empty set'
Here's a simple example:
test_set = {'word'}
print(test_set.pop() + ' and another word')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Marcin Cuprjak |
Solution 2 | KapJ1coH |