+2 votes
in Programming Languages by (11.1k points)

I created a set in python, but when I try to access an element of the set using index (like a list), it gives the following error:

>>> a=set([1,2,3,4])
>>> a[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>>


Is there any way to access an element of a set in python?

1 Answer

+1 vote
by (15.7k points)

You can convert the set to a list and then use index to access an element from the set.

>>> a=set([1,2,3,4])
>>> list(a)[1]
2
>>>

The set data structure does not care about the position of an element and that's why indexing is not supported. E.g.

>>> a=set([1,2,3,4,8,6,5,10,7]) 

- if you added you elements in the above order, it will be stored like the following. So, your input order is no more there and if you want to access elements as per your order, you will get the wrong element.
>>> a
set([1, 2, 3, 4, 5, 6, 7, 8, 10])

...