I don’t know why you need the global
declarations. It is best to avoid
global variables if possible. They make for code that is hard to
maintain.
You can iterate over a set by just iterating over it:
>>> myset = {12, 5, 9, 3, 11, 3}
>>> for i in myset:
... print(i)
...
11
9
3
12
5
Notice that:
So there is no way to ask “give me the third element in the set” because
the order is arbitrary. Obviously when you iterate over the set you will
see the elements in some order, but there is no way to control what
that order is. The order will depend on:
-
the version of Python you are using;
-
which elements are in the set;
-
and the history of the set: removing elements and re-adding them
can change the order.
If you need to control the order of the elements, use a list. The
disadvantage of a list is that searching is much slower than a set:
[steve ~]$ python3.9 -m timeit -s "data = set(range(100000))" "99999 in data"
10000000 loops, best of 5: 34 nsec per loop
[steve ~]$ python3.9 -m timeit -s "data = list(range(100000))" "99999 in data"
200 loops, best of 5: 1.18 msec per loop
On my computer, searching for 99999 in the list [0, 1, 2, ..., 99999]
is more than 34000 times slower than using a set. That is the cost you
pay to be able to access the elements by index.
If you need indexed access, use a list. If you need fast containment
checking, use a set.
Does this help? If not, please explain in detaik what you are trying to
do, because I don’t really understand your requirements.