[Tutor] Yet another list comprehension question

Kent Johnson kent37 at tds.net
Sat Mar 3 17:24:35 CET 2007


Andrei wrote:
>>> Alternatively, you could put the results as keys in a dictionary, 
>>> then request
>>> mydict.keys() to get a list of unique outcomes.
>> I thought of that too, but couldn't think how to do it in a list
>> comprehension. It seemed like it should be possible but I
>> couldn't think of how - and didn't have a python interpreter
>> handy...
> 
> I wouldn't do it in a list comprehension - I took a bit of liberty with 
> the topic and looked more at the actual problem :). Of course the loop 
> can be turned into a list comprehension, but it serves no purpose 
> whatsoever:
> 
>  >>> d = {}
>  >>> [d.__setitem__(s, '') for s in myiterator]
> 
> By the way, the fromkeys method of the dict type can turn this into a 
> oneliner:
> 
>  >>> mylist = [1,2,3,1,2,4] # may also be some iterator
>  >>> print dict.fromkeys(mylist).keys()
> ... [1,2,3,4]
> 
> The set solution is the Most Obvious Way to do it, but the dict one 
> doesn't require an understanding of list comprehensions.

The list comp in Alan's solution is just needed to introduce somefunc(). 
You have to do the same in yours to match the original problem. The set 
version of your solution doesn't need a list comp either, it is just
list(set(mylist))

There is really no reason in modern Python to use dicts as sets.

Kent


More information about the Tutor mailing list