Skip to content

Commit 207f5b3

Browse files
authored
Create lambda-functions.md
1 parent 7e51d9b commit 207f5b3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

python/lambda-functions.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Annonymous functions (Lambda functions)
2+
3+
Sometimes, naming a function is not worth the trouble. For example when you’re sure the function will only be used once. For such cases, Python offers us anonymous functions, also called lambda functions.
4+
5+
A lambda function can be assigned to a variable, creating a concise way of defining a function:
6+
7+
```python
8+
add_one = lambda x: x + 1
9+
add_one(3)
10+
# 4
11+
```
12+
13+
It gets more interesting when you need to use a function as an argument. In such cases, the function is often used only once. As you may know, `map` applies a function to all elements of an iterable object. We can use a lambda when calling map:
14+
15+
```python
16+
numbers = [1, 2, 3, 4]
17+
times_two = map(lambda x: x * 2, numbers)
18+
list(times_two)
19+
# [2, 4, 6, 8]
20+
```
21+
22+
In fact, this is a pattern that you’ll see often. When you need to apply a relatively simple operation on each element of an iterable object, using `map()` in combination with a lambda function is concise and efficient.

0 commit comments

Comments
 (0)