[Tutor] Yet another list comprehension question

Tim Golden mail at timgolden.me.uk
Fri Mar 2 18:26:26 CET 2007


Andrei wrote:
>> "Smith, Jeff" <jsmith <at> medplus.com> wrote
>>
>>> In other words, applying somefun to the results of the iterator 
>>> return
>>> duplicates but I want the constructed list to contain none.
>>> l = [somefun(i) for i some-iterator if somefun(i) not in l]
>>>
>>> doesn't work (not that I expected it to).
>> Why not use a Set?
>>
>> s = Set([somefun(i) for i in some-iterator])
>>
> 
> Alternatively, you could put the results as keys in a dictionary, then request
> mydict.keys() to get a list of unique outcomes.

While true, I wouldn't advocate that technique for any half-recent
version of Python. Sets have been supported -- first as an external
module, later as builtin -- since Python 2.3 (I think) with supported
modules before that, which may or may not have been based on dicts.
If you're *only* using a dict to remove the duplicates, better to
use a set. Obviously, if you need other facilities a dict offers you, 
say to associate something else to your keys, then it's the best thing

:)

TJG


More information about the Tutor mailing list