Functions are objects#
In Python, functions are values like numbers and strings. You can store them in variables and pass them to other functions:
A function that takes another function as an argument (like apply) is called a higher-order function. map, filter and sorted are built-in higher-order functions.
lambda - small anonymous functions#
lambda parameters: expression
A lambda is a one-line function without a name. It automatically returns the value of its expression.
The two definitions below are equivalent:
def square(x):
return x * x
square = lambda x: x * x
Lambda एक छोटा, बिना नाम का function है जो सिर्फ एक line में लिखा जाता है। इसमें return लिखने की ज़रूरत नहीं - expression का जवाब अपने आप return हो जाता है।
lambda x: x * x को ऐसे पढ़ें: "x लो, और x × x लौटा दो।"
Lambda का असली फायदा तब है जब किसी function (जैसे sorted, map, filter) को एक छोटा-सा "नियम" देना हो, और उसके लिए पूरा def लिखना ज़रूरत से ज़्यादा लगे।
Lambdas are for short, throw-away functions. If you're assigning a lambda to a name (like square = lambda ...), a regular def is usually clearer. Use lambda mainly inline, as an argument.
map() - transform every item#
map(function, iterable) applies the function to each item and gives back the results:
map returns a lazy map object, not a list. Wrap it in list() to see the values, or loop over it directly. This is also why map(int, input().split()) works for reading numbers.
filter() - keep matching items#
filter(function, iterable) keeps only the items where the function returns True:
sorted(), max(), min() with key=#
The key parameter takes a function that returns the value to compare:
Sorting a list of dictionaries:
reduce() - combine into one value#
reduce (from the functools module) repeatedly combines items into a single result:
map/filter vs comprehensions#
The same results can often be written as list comprehensions (coming in a later lesson), which many Python developers find more readable:
squares = list(map(lambda n: n * n, nums))
squares = [n * n for n in nums] # comprehension
evens = list(filter(lambda n: n % 2 == 0, nums))
evens = [n for n in nums if n % 2 == 0] # comprehension
Both styles are correct - you should be able to read both.
Summary#
- Functions are objects; they can be passed to other functions.
lambda args: expressioncreates a small anonymous function.map(f, items)transforms each item;filter(f, items)keeps items where f is True.sorted,max,minacceptkey=to choose what to compare.functools.reducecombines items into one value.