2-4 Raw Python - Lambda Functions


Raw Python - Lambda Functions


In [1]:
x = range(10)

In [2]:
x


Out[2]:
range(0, 10)

In [3]:
[item**2 for item in x]


Out[3]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [4]:
def square(num):
    return num**2

In [9]:
list(map(square, x))


Out[9]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [10]:
square_lamb = lambda num: num**2

In [11]:
list(map(square_lamb, x))


Out[11]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Lambda functions are just anonymous functions and don't need to be created as official functions prior to being used. This makes them useful because they can really help with code readability (if used appropriately). Their true power comes from their expressiveness when performing inline operations.

I'm sure that sounds abstract at this point but I figured it would lay good ground work for our example


In [12]:
list(map(lambda num: num**2, x))


Out[12]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

square every number that is divisible by 2 from 1 to 20


In [13]:
[item**2 for item in range(1,20) if item % 2 == 0]


Out[13]:
[4, 16, 36, 64, 100, 144, 196, 256, 324]

That’s a little abstract at this point...

We'll get to those with map, filter, and reduce below

Now obviously this is not appropriate for everything but I just want you to understand that lambda functions are just anonymous functions.


In [15]:
list(map(lambda z: z**2, filter(lambda z: z % 2 == 0, range(1,20))))


Out[15]:
[4, 16, 36, 64, 100, 144, 196, 256, 324]

Now that we covered these raw python basics. We can start moving on to some of the better things. However before we move onto pandas, it is worth introducing the ipython notebook. This is installed with the anaconda distribution and ipython is a very powerful tool.


In [ ]: