python – How to access the elements of a set (set)?

Question:

I'm studying sets ( set ) in Python because I'm going to use it in an algorithm to find paths in a graph, it's for a college course I'm taking.

I created two set examples using two different notations. Look at the example illustration:

foo = {1, 1, 5, 'gato', 'Oie'}
baz = set([2, 19, 51, 'stack', 'py'])

print(foo)
print(baz)

However, when I try to access some value from the two sets foo or baz using baz[0] indexing it returns an error saying that the object does not support indexing, see:

Traceback (most recent call last):
  File "jdoodle.py", line 11, in <module>
    print(baz[2])
TypeError: 'set' object does not support indexing
Command exited with non-zero status 1

Question

Therefore, I would like to know how I could access the elements of a set individually?

Answer:

Python's set data structure has no ordering – so it wouldn't make sense to say "give me the element at position 0" (myset[0]) – however it is iterable!

So if you have an action to perform with each element of a set, you can simply do:

for element in my_set:
    # do things with 'element'

That's enough, and the most correct way for most cases. If you really need to do a lot of operations on arbitrary set elements, you can put those elements in a list – just like an iterable:

minha_lista = list(meu_set)

It works – but the list won't be in any particular order – (so why not use the for above). If you need some sorting, you can use the sorted built-in which returns a list but sorts the elements – so if you want the elements in alphabetical order:

 minha_lista = sorted(meu_set)  

Or, if you want arbitrary ordering, you can use the key parameter for sorted – let's say you want a list of the elements in your set in ascending order of length:

minha_lista = sorted(meu_set, key=len) 

This will use the return from the len function on each item to do the sorting. Details about sorted are that the elements of the set are compared against each other, so it wouldn't work for the sets with mixed object types from your examples (it might work if you write a key function that works for the various object types).

Scroll to Top