user1157504
user1157504

Reputation: 81

Python 'set' object does not support indexing

I am working on a Windows 7 os in a Python (3.2.2) shell. Trying to learn the language I entered and had returned the following:

>>> cast = {
    'cleese',
    'Palin',
    'Jones',
    'Idle'
    }
>>> print (cast[1])
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    print (cast[1])
TypeError: 'set' object does not support indexing
>>> cast.append('Gilliam')
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    cast.append('Gilliam')
AttributeError: 'set' object has no attribute 'append'

==========================

It seems as if the problem is not in the coding, but with how the program was installed.

I have installed, un-installed and installed again, but the resutl is the same. I there something I need to do before Python's shell is ready to be used?

hans

Upvotes: 8

Views: 49854

Answers (3)

user1767754
user1767754

Reputation: 25094

Just to mention in here, set's' do not support indexing, as they are hash based, it is very similar to dictionaries which don't support indexing as well. You can only access a dict by it's key.

If you need indexing, you can convert your set as follows:

convertedToList = list(set(1,2,3))

Upvotes: 3

Yang Meng
Yang Meng

Reputation: 41

It seems that you were trying to define a list. However, you used braces {} instead of brackets []. The interpreter treated it as a dictionary rather than a list, so indexing and append() didn't work here.

Upvotes: 4

Daniel Fischer
Daniel Fischer

Reputation: 183858

Python seems to work fine. The point is that set doesn't support indexing or appending. Try using a list instead ([] instead of {}). In place of appending, set has add, but indexing is out.

And Python has useful help,

>>> help(set)

prints a lot of info about sets.

Upvotes: 20

Related Questions