Python 'set' object does not support indexing

I am working on Windows 7 in the Python shell (3.2.2). Trying to learn the language I introduced and 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 that the problem is not in coding, but in how the program was installed.

I installed, did not install, and installed again, but resutl is the same. Do I have to do something before the Python shell is ready to use?

Hans

+6
source share
3 answers

Python is working fine. The fact is that set does not support indexing or adding. Instead, try using a list ( [] instead of {} ). Instead of adding, set has add , but no indexing.

And Python has some helpful help,

 >>> help(set) 

prints a lot of information about set s.

+18
source

It seems you were trying to define a list. However, curly braces {} were used instead of brackets []. The interpreter viewed it as a dictionary, not a list, so indexing and append () did not work here.

+4
source

To just mention here, set's' don't support indexing, since they are based on a hash, it is very similar to dictionaries , which also does not support indexing. Access to dict can only be accessed with key .

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

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

Source: https://habr.com/ru/post/906359/


All Articles