Lambda Functions¶
Lambda functions are "disposable" nameless functions. They are often used as arguments in other functions. For example:
In [1]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = lambda p : p[1])
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
The expression "lambda p : p[1]" defines a nameless function equivalent to the following (see its visualization here):
In [2]:
def getkey(p):
return p[1]
In [3]:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key = getkey)
print(pairs)
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
The following is another example where we use a lambda function to extract from a list with the filter command:
In [4]:
squares = [x ** 2 for x in range(100)]
sq = list(filter(lambda x : x % 2 == 0 and x % 3 == 0, squares))
sq
Out[4]:
[0, 36, 144, 324, 576, 900, 1296, 1764, 2304, 2916, 3600, 4356, 5184, 6084, 7056, 8100, 9216]
It is equivalent to the following:
In [5]:
def multiple_of_6(x):
return x % 2 == 0 and x % 3 == 0
squares = [x ** 2 for x in range(100)]
sq = list(filter(multiple_of_6, squares))
sq
Out[5]:
[0, 36, 144, 324, 576, 900, 1296, 1764, 2304, 2916, 3600, 4356, 5184, 6084, 7056, 8100, 9216]
'Python' 카테고리의 다른 글
| 9. Regular Expression (0) | 2024.03.14 |
|---|---|
| 8. Text File I/O (0) | 2024.03.14 |
| 6. Recursion vs. Iteration (1) | 2024.03.14 |
| 5. Function (0) | 2024.03.14 |
| 4. Conditionals and Loops (0) | 2024.03.14 |
