Lambda expressions
Created on Jan. 17, 2017 by Julien Palard
Presentation
A function can be expressed in a concise way called lambda expression. More generically, it's called an "anonymous function" because it doesn't have a name.
The function syntax is:
1 2 |
|
The lambda syntax is:
1 |
|
As you see it has no name, and it's very concise.
It's particularly useful in order to give a minimalist function directly as a parameter of another function, typically, the builtin sorted.
1 2 3 |
|
In this exercise, you'll write a function named filtered
, taking
two parameters: an iterable
, typically a list, and a filter
, a
lambda expression.
Your function filtered
should return an iterable
(a list for example).
1 2 3 4 5 6 7 |
|
Obviously your filtered
function should also work if passed a function name
instead of a lambda
expression.
1 2 3 4 5 6 7 8 9 10 |
|
(Now you see why we use lambda.)
After your filtered
function, you'll write three lines using your
filtered function and lambdas:
- print all numbers from 0 to 100 included that are multiple of 3
- print all numbers from 0 to 100 included that are multiple of 5
- print all numbers from 0 to 100 included that are multiple of 15
Numbers should be separated by comas, one list per line, such as:
1 2 3 |
|