The thing to remember is a function is defined (via def
or lambda
) in a certain environment or scope. In your example function, the lambdas are defined inside of foo()
and therefore have access to foo
's local variables (like n
). When smaller_then_ten
is defined outside of foo
, it doesn't have access to the variable n
. Kwarrtz and Nikita each showed ways to solve that issue. However, the easiest way is to define the new function in the same environment that the lambdas where in, like so:
def foo(los, n=None):
def smaller_than_n(tpl):
return tpl[0] < n
def item1(tpl):
return tpl[1]
def const1(i):
return 1
def count(key, values):
return key, sum(map(const1, values))
n = n or len(los)
h = it.takewhile(smaller_than_n, enumerate(los))
s = sorted(h, key=item1)
g = it.groupby(s, key=item1)
return dict(it.starmap(count, g))
As you are learning Python, get familiar with the standard library. It is a great resource. To pique your interest: the first two lines of foo()
could be replaced by itertools.islice
, item1()
could be replaced by operator.itemgetter
, and the whole foo
function could be replaced by collections.Counter
.