I have implemented a lambda function to sort a list. now i want to remove all the negative objects from the list by using lambda functions .

dto_list.sort(key=lambda x: x.count, reverse=True)

any one know a way to write the lambda expression to do it? I could not find a proper tutorial

share|improve this question
2  
Do you have to use a lambda? Usually they are unnecessary and make code less readable. – jamylak May 16 '12 at 7:43
    
yep have to use lambda – Evlikosh Dawark May 16 '12 at 7:44
    
FYI the pythonic way to do the above is sorted(dto_list, key=operator.attrgetter("count"), reverse=True) – katrielalex May 16 '12 at 8:10
up vote 9 down vote accepted

Not very pythonic but here is how to do it with a lambda

>>> L = list(range(-10,10))
>>> L
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x >= 0, L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Most people would use a list comprehension

>>> [x for x in L if x >= 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
share|improve this answer
3  
Hey thank you very much – Evlikosh Dawark May 16 '12 at 7:50
    
any one know python standards for list operations ? whether to use lambda functions? what are the good practices ? – Kalanamith May 16 '12 at 8:08
3  
@Kalanamith: The "standard" is to use whatever is shortest and easiest to understand. Sometimes that will be a list comprehension; sometimes it will be itertools; sometimes that will be a lambda function used with map(), filter(), or reduce(). You get to make the call as to which one is better for your application. – Li-aung Yip May 16 '12 at 8:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.