Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'set' object does not support indexing

I've just been doing some random stuff in Python 3.5. And with 15 minutes of spare time, I came up with this:

a = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
 "x", "y", "z"}
len_a = len(a)
list = list(range(0, len_a))
message = ""
wordlist = [ch for ch in message]
len_wl = len(wordlist)
for x in list:
    print (a[x])

But that satisfying feel of random success did not run over me. Instead, the feeling of failure did:

Traceback (most recent call last):
File "/Users/spathen/PycharmProjects/soapy/soup.py", line 9, in  <module>
print (a[x])
TypeError: 'set' object does not support indexing

Please help

like image 522
Sakib Pathen Avatar asked May 16 '17 01:05

Sakib Pathen


2 Answers

Try square brackets:

a = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
 "x", "y", "z"]

i.e.: use an list instead of a set

like image 85
lostbard Avatar answered Oct 10 '22 03:10

lostbard


As the error message says, set indeed does not support indexing, and a is a set, since you used set literals (braces) to specify its elements (available since Python 3.1). However, to extract elements from a set, you can simply iterate over them:

for i in a:
    print(i)
like image 31
Andrzej Pronobis Avatar answered Oct 10 '22 04:10

Andrzej Pronobis