52

Can I use lambda expression to count the elements that I'm interested? For example, when I need to count the elements in a list that is more than two, I tried this code which returns 0.

x = [1,2,3]
x.count(lambda x: x > 2)
3
  • 2
    This code doesn't return anything. You have a syntax error. Don't type from memory, copy/paste code that demonstrably works. Commented Sep 26, 2011 at 0:22
  • Why do you want to use lambdas? Commented Sep 26, 2011 at 0:24
  • 3
    Your code counts how often this particular lambda object is in the list. Commented Sep 26, 2011 at 0:39

3 Answers 3

49

Note: "more than" is > ... => is not a valid operator.

Try sum(y > 2 for y in x)

Or, as suggested by @Jochen, to guard against non-conventional nth-party classes, use this:

sum(1 for y in x if y > 2)

Sign up to request clarification or add additional context in comments.

4 Comments

Summing booleans. Nice. +1 for demonstrating that lambda is not necessary.
or sum(1 for y in x if y > 2)
@TokenMacGuy: or it could be decimal, or rational, or some weird DIY class; whatever y is, surely y > 2 should not run amok. I don't see the point of float(y). Yes, some badass class could define comparison operators that return neither True nor 1 for truthy results -- in which case, the suggestion of @Jochen [Thanks!] avoids the explicit bool()
sum(1 for y in x if y > 2) is IMHO the best and most Pythonic answer.
21

You can try any of the following

len([y for y in x if y > 2])

or

len(filter(lambda y: y > 2, x))

or the nicer

sum( y > 2 for y in x )

4 Comments

OP wanted "more than two", not "more than or equal to two".
I tried the second option. But it says 'filter' has no len.
@vijayst This answer is from 2011 and thus for Python 2.7. filter returns a generator in Python 3.x meaning that suggested method is no longer applicable.
Second option just needs the filter wrapping in list() to work with Python3 : len(list(filter(lambda y: y > 2, x)))
4
from functools import reduce

x = [1,2,3]
reduce(lambda a,i: a+1 if (i>2) else a, x, 0)

This will not create a new list. a is the accumulator variable, i is the item from the list, and the 0 at the end is the initial value of the accumulator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.