Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TypeError: 'set' object is not subscriptable

Tags:

python

def create(ids):
    policy = {
        'Statement': []
    }
    for i in range(0, len(ids), 200):
        policy['Statement'].append({
            'Principal': {
                'AWS': list(map(lambda id: f"arn:aws:iam::{id}:root", ids[i:i + 200]))
            }
        })
    return policy

when I make a function call to this method create({'1','2'}) I get an TypeError: 'set' object is not subscriptable error on line 'AWS': list(map(lambda id: f"arn:aws:iam::{id}:root", ids[i:i + 200])). Coming from a java background, is this somehow related to typecasting? Does the error mean that I'm passing a set data structure to a list function? How could can this be resovled?

like image 474
user2118245 Avatar asked Nov 26 '19 00:11

user2118245


2 Answers

As per the Python's Official Documentation, set data structure is referred as Unordered Collections of Unique Elements and that doesn't 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 there's 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
like image 139
CHINTAN VADGAMA Avatar answered Sep 17 '22 18:09

CHINTAN VADGAMA


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

like image 30
caroline mwasigala Avatar answered Sep 16 '22 18:09

caroline mwasigala