Zee Shan Zee Shan - 1 month ago 25
Python Question

TypeError: 'set' object has no attribute '__getitem__'

I am trying to create a list of lists using recursion in Python.

For example:

li = [1,2,3,4,5] // given list

listoflists = [[1,2,3,4,5],[2,3,4,5],[3,4,5],[4,5],[5]]//required list


def recur(li,index,perlist):
if(index==3):
return
else:
templi = li[index:len(li)]
perlist.append(templi)
recur(li,index+1,perlist)

li = {1,2,3}
perlist = []
recur(li,0,perlist)
print perlist


It throws following error:

TypeError: 'set' object has no attribute '__getitem__'

Answer Source

As the other users have pointed out, lists are made with [] brackets.

def recur(li,index,perlist):
    if(index==3):
       return
    else:
      templi = li[index:len(li)]
      perlist.append(templi)
      recur(li,index+1,perlist)

li = [1,2,3]
perlist = []
recur(li,0,perlist)
print perlist

works fine, giving output

[[1, 2, 3], [2, 3], [3]]

The {} brackets may be a habit from some C-like language, but in Python, a list of items in {} brackets is a set (HashSet). The important distinction is that a set is unordered, and is used for membership testing, whereas a list is ordered, and supports indexing and iteration. "has no attribute '__getitem__'" means that a set does not support indexing. This has to do with that something like l[0] actually becoming l.__getitem__(...). Note that {} brackets are also used for making dicts (HashMap, associative array..), but that's with a colon -

In more demonstrative terms:

>>> a = {1, 2, 3}
>>> b = [1, 2, 3]
>>> c = {1: "x", 2: "y", 3: "z"}

a is a set,

b is a list,

c is a dict