[Tutor] How to get at the list that set() seems to produce?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 28 21:17:48 CEST 2006


> I'm wondering if there isn't a way to get at what seems to be the
> list of unique elements set() seems to produce.

Here you go:

#############################################
>>> list(set(['e', 'q', 'r', 't', 'w', 'y']))
['e', 'q', 'r', 't', 'w', 'y']
#############################################

Just to head off any confusion here: this is not type coersion or type 
casting.  list() is just a regular function that takes an iterable and 
returns a list of that iterable's elements.  We can just as easily 
"listify" other iterable things such as strings.

##############################
>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']
##############################



> >>> set(['e', 'q', 'r', 't', 'w', 'y'])[:]
> Traceback (most recent call last):
>   File "<string>", line 1, in <string>
> TypeError: 'set' object is unsubscriptable
> >>> set(['e', 'q', 'r', 't', 'w', 'y'])[0]
> Traceback (most recent call last):
>   File "<string>", line 1, in <string>
> TypeError: 'set' object is unindexable
>
> To be sure I'm clear, I'm not asking how to do the above things in
> other ways (I know how)--I'm just wondering why set() was set up
> (pun) so they can't be done with its help.

A "set" is a concept that provides support for operations that are listed 
in:

     http://www.python.org/doc/lib/types-set.html

When we say something is a "set", we don't automatically assume that it 
can be indexed or sliced.  The reason for that is because sets may not 
necessarily be represented as lists; a perfectly good implementation of 
sets can be implemented using something else entirely such as binary trees 
or dictionaries.

Concretely, if we use a dictionary implementation for the concept of a 
set, then asking for a set's slice or element index is a "nonsensical" 
operation: what is it supposed to mean, if all the elements are scattered 
around in no particularly meaningful order?  So that's a good reason to 
leave sequencing-dependent operations outside of the definition of a set.


More information about the Tutor mailing list