Reputation:
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
Upvotes: 10
Views: 61629
Reputation: 29
@Sakib, your set a
is already iterable. 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 )
Additionally, your code doesn't show enough intent for us to help you get to your ultimate goal. Examples:
range()
also returns an iterable type, so there's no reason to convert it to a list
list
keyword, and it doing so will lead to many more problemslen_wl
doesn't serve a purpose yetwordlist
nor message
have a purpose eitherHope this helps
PS - don't forget to select an answer
Upvotes: 2
Reputation: 1941
try to modify 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 doesn't support indexing however list support it, so here i convert set to list and get index of list.
Upvotes: -1
Reputation: 5230
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
Upvotes: 11
Reputation: 36146
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)
Upvotes: 6