Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Sets Out Of This Word Game

Yu-Chien Huang
PLUS
Yu-Chien Huang
Courses Plus Student 16,672 Points

could any one tell me whats going with the error:TypeError: 'set' object does not support indexing? thank u

after i ran mu code, i got feedback from terminal: Traceback (most recent call last): File "set_wordgame.py", line 21, in <module> challenge_word = random.choice(WORDS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/random.py", line 259, in choice return seq[i] TypeError: 'set' object does not support indexing

=>well , i dont know what happened, could anyone help ? thank u!

Steven Parker
Steven Parker
229,732 Points

You'll need to share more of the code to make it possible to analyze the issue.
A great way to share code is to make a snapshot of your workspace and post the link to it here.

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

I don't know if this will help you but sets are not considered to be "ordered". The only way to impose an order and use index operations is to convert the set to a list. See an example below. Notice that when it is a list, I can access the elements by their numeric index, when it is a set it throws an error.

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> beatles = {'John Lennon','Paul McCartney','Ringo Star','George Harrison'}
>>> beatles
{'George Harrison', 'John Lennon', 'Paul McCartney', 'Ringo Star'}
>>> beatles.index('Ringo Star')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'index'
>>> beatles_list = list(beatles)
>>> beatles_list
['George Harrison', 'John Lennon', 'Paul McCartney', 'Ringo Star']
>>> beatles_list.index('Ringo Star')
3
>>> beatles[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
>>> beatles_list[3]
'Ringo Star'
>>>

If anyone else runs into this problem, in my case it's because I used { } instead of ( ) in the WORDS tuple.

Steven Parker
Steven Parker
229,732 Points

A great example of why short excerpts aren't always enough to spot a problem! But congratulations on finding it.