Pythonic way of count


Writing code in a clean way differs in every language. Python also has its own style. Additionally, python is famous about its one-liners.

Pythonic way is an approach of how to use the language and how to take adventage of its syntax and semantic. Python can give a very elegant way of one-liners to achieve something that most of the languages can do, but not as short and still readable way as python does it.

Let’s see the next exercise:

Count the values in a list.

len

Usually we use len built-in.

>>> arr = [1, 2, 3, 1, 2, 3, 0]
>>> len(arr)
# => 7

sum

My pythonic way of count is here. For counting we can use the built-in sum like:

>>> arr = [1, 2, 3, 1, 2, 3, 0]
>>> sum(1 for x in arr)
# => 7

With condition

What if I want to count just those items that are equivalent to 2.

>>> arr = [1, 2, 3, 1, 2, 3, 0]
>>> sum(1 for x in arr if 2 == x)
# => 2 

What if I want to apply a predicate on the item in the current iteration?

>>> arr = [1, 2, 3, 1, 2, 3, 0]
>>> even = lambda i: i % 2 == 0
>>> sum(1 for x in arr if even(x))
# => 3

Pythonic way of count is elegant, short and still understandable.