Python TypeError: set object is not subscriptable

Python TypeError: set object is not subscriptable

As per the Pythons Official Documentation, set data structure is referred as Unordered Collections of Unique Elements and that doesnt support operations like indexing or slicing etc.

Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

When you define temp_set = {1, 2, 3} it just implies that temp_set contains 3 elements but theres no index that can be obtained

>>> temp_set = {1,2,3}
>>> 1 in temp_set
>>> True
>>> temp_set[0]
>>> Traceback (most recent call last):
  File /usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py, line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File <ipython-input-10-50885e8b29cf>, line 1, in <module>
    temp_set[0]
TypeError: set object is not subscriptable

I faced the same problem when dealing with list in python

In python list is defined with square brackets and not curly brackets

wrong List {1,2,3}

Right List [1,2,3]

This link elaborates more about list
https://www.w3schools.com/python/python_lists.asp

Python TypeError: set object is not subscriptable

Like @Carcigenicate says in the comment, sets cannot be indexed due to its unordered nature in Python. Instead, you can use itertools.islice in a while loop to get 200 items at a time from the iterator created from the given set:

from itertools import islice

def create(ids):
    policy = {
        Statement: []
    }
    i = iter(ids)
    while True:
        chunk = list(islice(i, 200))
        if not chunk:
            break
        policy[Statement].append({
            Principal: {
                AWS: list(map(lambda id: farn:aws:iam::{id}:root, chunk))
            }
        })
    return policy

Leave a Reply

Your email address will not be published. Required fields are marked *