8
I’m studying about ensembles (set
) in Python because I’m going to use it in an algorithm to find paths in a graph, it’s for a college discipline that I’m having.
I created two set examples using two distinct notations. Look at the illustration example:
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 of the two sets foo
or baz
using indexing baz[0]
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?
"For some reason" > The reason is that elements of
set
do not have "order" so they cannot be indexed in a way that makes sense. When converting to list withlist(a)
as you did, there’s no way to guarantee that the element1
be the first on the list, it may fall into another position. One way is to usesorted(a)
which ensures that the elements will be in numerical order.– nosklo
I still haven’t had to add more reference, I’m stuck here, kkkkk.
– Wallace Maxters
In these answers from Soen there are some ways to keep order. In the first example, with an entry
[2, 60, 19, 51, 'stack', 'py', 60, 'stack']
the exit is[2, 60, 19, 51, 'stack', 'py']
– danieltakeshi