Fix: TypeError: set object is not subscriptable

We get a TypeError that the set object is not subscriptable when we try to access the elements of a set in Python like a list or a tuple.


Reason for the Error:

    We cannot access elements of a set using indexing e.g. data[0] like lists or tuples.


Example of the Error:

    data_set = {12, 121, 9, 14}
    print(data_set[0])
    Traceback:
    TypeError Traceback (most recent call last)
    
    <ipython-input-4-174921f67730> in <cell line: 2>()
          1 data_set = {12, 121, 9, 14}
    ----> 2 print(data_set[0])
    
    TypeError: 'set' object is not subscriptable
    Python Error - TypeError - set object is not subscriptable

How to fix the Error:

    To access elements of a set in Python, you can do one of the following,

    1. Iterate the set using for loop.
      data_set = {12, 121, 9, 14}
      
      for element in data_set:
          print(element)
      
    2. Convert set to a list to access using an index:
      data_set = {12, 121, 9, 14}
      data_list = list(data_set)
      
      print(data_list[0])

    Comments & Discussion

    Facing issues? Have questions? Post them here! We're happy to help!