[Tutor] Yet another list comprehension question

Andrei project5 at redrival.net
Sat Mar 3 16:43:00 CET 2007

>> 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 

 >>> d = {}
 >>> [d.__setitem__(s, '') for s in myiterator]

By the way, the fromkeys method of the dict type can turn this into a 

 >>> 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.



Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss  edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])

More information about the Tutor mailing list