python - TypeError: 'set' object has no attribute '__getitem__' -
i trying create 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__'
as other users have pointed out, lists made [] 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 habit c-like language, in python, list of items in {} brackets set (hashset). important distinction set unordered, , used membership testing, whereas list ordered, , supports indexing , iteration. "has no attribute '__getitem__'" means set not support indexing. has l[0] becoming l.__getitem__(...). note {} brackets used making dicts (hashmap, associative array..), that's colon -
in more demonstrative terms:
>>> = {1, 2, 3} >>> b = [1, 2, 3] >>> c = {1: "x", 2: "y", 3: "z"} a set,
b list,
c dict
Comments
Post a Comment