TypeError: object 'set' does not support indexing
I just did some random stuff in Python 3.5. And with 15 minutes of free 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 the satisfaction with a sense of accidental success did not surpass me. Instead, a sense of failure:
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
+3
source to share
4 answers
try changing your code like 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"}
list_a = list(a)
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 list_a[x]
set does not support indexing, but list does, so here I am converting set to list and getting the index of the list.
0
source to share
@Sakib, your set is a
already iterating over. Please consider using this updated code instead of accessing elements by index.
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"}
for x in a:
print ( x )
Also, your code doesn't show enough intent for us to help you achieve your ultimate goal. Examples:
-
range()
also returns an iterable type, so there is no reason to convert it tolist
- It's not a bad practice to reuse (rewrite) a keyword
list
, and this will lead to even more problems. -
len_wl
does not serve the purpose - Because of # 3 neither
wordlist
, normessage
have a purpose either
Hope it helps
PS - don't forget to choose an answer
0
source to share