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

Kent Johnson kent37 at tds.net
Thu Sep 28 20:55:57 CEST 2006


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:
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.

Kent



More information about the Tutor mailing list