-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLambda_Expressions.py
More file actions
66 lines (39 loc) · 1.67 KB
/
Lambda_Expressions.py
File metadata and controls
66 lines (39 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python
# coding: utf-8
# # Lambda Expressions
# ### - Expression used to create on anonymous function (i.e., functions that don't have a name)
# ## Example
# ### - Regular Function
# In[14]:
def double(x):
return x * 2
# ### - Equivalent Lambda Expression
# In[28]:
double = lambda num: num * 2
double = lambda x: x * 2 # lambda ----> keyword
# x ----> following lambda or one or more arguments for the anonymous function and then a colon
double(3)
# lambda x, y: x * y (remove comment for test purposes)
# # Lambda with Map
# ### - map() is a higher-order built-in function that makes a function and iterable as inputs and returns an iterator that applies the function to each element of the iterable.
# In[36]:
# Given a list of lists containing numbers
numbers = [
[34, 63, 88, 71, 29],
[90, 78, 51, 27, 45],
[63, 37, 85, 46, 22],
[51, 22, 34, 11, 18]
]
# Use the map() function with a lambda expression to calculate the average for each sublist
averages = list(map(lambda x: sum(x) / len(x), numbers))
# Print the resulting list of averages
print(averages)
# # Lambda with Filter
# ### - filter() is a higher-order built-in function that takes a function and iterable as inputs and returns an itertor with the elements from the iterable for which the function returns True.
# In[34]:
# Given a list of cities
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]
# Use the filter() function with a lambda expression to filter cities with names shorter than 10 characters
short_cities = list(filter(lambda x: len(x) < 10, cities))
# Print the resulting list of short cities
print(short_cities)