Converting a set into list
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun May 15 12:28:05 EDT 2011
On Mon, 16 May 2011 00:05:44 +0800, TheSaint wrote:
> Chris Torek wrote:
>
>> >>> x = ['three', 'one', 'four', 'one', 'five'] x
>> ['three', 'one', 'four', 'one', 'five']
>> >>> list(set(x))
>> ['four', 'five', 'three', 'one']
>
> Why one *"one"* has purged out?
> Removing double occurences in a list?
Break the operation up into two steps instead of one:
>>> x = ['three', 'one', 'four', 'one', 'five']
>>> s = set(x)
>>> print s
set(['four', 'five', 'three', 'one'])
>>> list(s)
['four', 'five', 'three', 'one']
Once an element is already in a set, adding it again is a null-op:
>>> s = set()
>>> s.add(42)
>>> s.add(42)
>>> s.add(42)
>>> print s
set([42])
--
Steven
More information about the Python-list
mailing list