Converting a set into list

Chris Torek nospam at torek.net
Sat May 14 22:11:11 EDT 2011


In article <871v00j2bh.fsf at benfinney.id.au>
Ben Finney  <ben+python at benfinney.id.au> wrote:
>As pointed out: you already know how to create a set from an object;
>creating a list from an object is very similar:
>
>    list(set(aa))
>
>But why are you doing that? What are you trying to achieve?

I have no idea why someone *else* is doing that, but I have used
this very expression to unique-ize a list:

    >>> x = [3, 1, 4, 1, 5, 9, 2, 6]
    >>> x
    [3, 1, 4, 1, 5, 9, 2, 6]
    >>> list(set(x))
    [1, 2, 3, 4, 5, 6, 9]
    >>>

Of course, this trick only works if all the list elements are
hashable.

This might not be the best example since the result is sorted
"by accident", while other list(set(...)) results are not.  Add
sorted() or .sort() if needed:

    >>> x = ['three', 'one', 'four', 'one', 'five']
    >>> x
    ['three', 'one', 'four', 'one', 'five']
    >>> list(set(x))
    ['four', 'five', 'three', 'one']
    >>> sorted(list(set(x)))
    ['five', 'four', 'one', 'three']
    >>> 
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list