lambda question

Ian Kelly ian.g.kelly at gmail.com
Sat Jun 12 00:11:30 EDT 2010


On Fri, Jun 11, 2010 at 9:31 PM, Vincent Davis <vincent at vincentdavis.net> wrote:
> Starting with an example.
> In [23]: x = [1,2,3,4,4,4,5,5,3,2,2,]
> In [24]: y = set(x)
> In [25]: y
> Out[25]: set([1, 2, 3, 4, 5])
> In [26]: y2 = len(set(x))
> In [27]: y2
> Out[27]: 5
>
> How would I do the above "y2 = len(set(x))" but have len(set()) in a
> dictionary. I know how to do ..
> In [30]: d = dict(s=set)
> In [32]: d['s'](x)
> Out[32]: set([1, 2, 3, 4, 5])
>
> but not sure how to add the len() and thought maybe the answer in a
> lambda function.
> I know I could def a function but would prefer to keep it all on one line.

>>> d = dict(s=lambda x: len(set(x)))
>>> d['s'](x)
5

Cheers,
Ian



More information about the Python-list mailing list