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

Dick Moores rdm at rcblue.com
Thu Sep 28 21:35:08 CEST 2006


At 11:55 AM 9/28/2006, Kent Johnson wrote:
>Dick Moores wrote:
> > I'm very interested in the data type, set.
> >
> > Python 2.5:
> >  >>> lst = [9,23,45,9,45,78,23,78]
> >  >>> set(lst)
> > set([9, 45, 78, 23])
> >  >>> s = "etywtqyertwytqywetrtwyetrqywetry"
> >  >>> set(s)
> > set(['e', 'q', 'r', 't', 'w', 'y'])
> >  >>>
> >
> > 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. For example, I would
> > think it might be useful if the "list" of set([9, 45, 78, 23]) could
> > be extracted, for sorting, taking the mean, etc.
>
>You just have to ask:

(as usual, I'm glad I did :) )

>In [1]: lst = [9,23,45,9,45,78,23,78]
>
>In [2]: set(lst)
>Out[2]: set([9, 45, 78, 23])
>
>In [3]: list(set(lst))
>Out[3]: [9, 45, 78, 23]
>
> > And it might be nice
> > if the "list" of set(['e', 'q', 'r', 't', 'w', 'y']) could be
> > converted into the sorted string, "eqrtwy".
>
>In [4]: s = "etywtqyertwytqywetrtwyetrqywetry"
>
>In [5]: ''.join(sorted(set(s)))
>Out[5]: 'eqrtwy'
>
>The key concept is that a set is iterable - it's not a list, but in
>contexts that accept an iterable it will work the same as a list.

Got it. Thanks much, Kent.

Dick





More information about the Tutor mailing list