Is there any advantage or disadvantage to using sets over list comps to ensure a list of unique entries?

Raymond Hettinger python at rcn.com
Sat Jun 25 04:05:19 EDT 2011


On Jun 20, 9:43 pm, deathweaselx86 <deathwea... at gmail.com> wrote:
> Howdy guys, I am new.
>
> I've been converting lists to sets, then back to lists again to get
> unique lists.
> e.g
>
> Python 2.5.2 (r252:60911, Jan 20 2010, 21:48:48)
> [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> foo = ['1','2','3']
> >>> bar = ['2','5']
> >>> foo.extend(bar)
> >>> foo = list(set(foo))

That works great and is very clear.

If you want to also preserve order, use an OrderedDict:

>>> list(OrderedDict.fromkeys('abracadabra'))
['a', 'b', 'r', 'c', 'd']


Raymond



More information about the Python-list mailing list