l = [1,1,3,3,4,1,1,1,1,1,1,1,1,7000]
elem = 1;
# Terse method to find count of elem
cnt_of_1 = len([i for i in l if i == elem])
# Verbose method to find count of elem
cnt = 0
for i in l:
if i == elem:
cnt += 1
Between the two approaches which is a more pythonic code and why? I do realize in the terse approach, python will be internally creating a new list and iterating through the list to find the length of the new list; hence increasing the space complexity to O(n)
. As opposed to the more verbose code, which has a space complexity O(1)
since the only extra space required is the integer cnt variable.
As for readability, I prefer the first approach as it's a single line with a relatively simple logic, hence allowing me to skip the line and maintaining my focus on bigger picture (may be domain or an algorithm related focus).
I would like people's thoughts here.