Python is Awesome: Lambda Functions & Map

in #mathematics7 years ago

Python is Awesome!


Python is, by far, my favorite programming language. This is largely due to the inclusion of lambda functions and some awesome built-in functions which allow for neat functional programming.


Normally in python, you define functions like this:

def f(x):
    return x**2

but you can also define functions inline like this:

f = lambda x:x**2

Simple functions like this come in very handy...for instance let's say you want to sort a list of strings alphabetically, but ignoring the first character:

words = ["hello", "world", "this", "is", "an", "example"]
sorted_words = sorted(words,key = lambda x: x[1:])

This yields the following list: ['hello', 'this', 'an', 'world', 'is', 'example'].
Note that we passed the lambda function as an argument so it knows how to compare elements of the list!
This type of thing can be very useful for dealing with dictionaries (dicts).

You can also use the built-in functions "max", "min", and "sum" similarly:

l = [1,2,3,4,5]
m1 = max(l) #5
m2 = min(l) #1
s = sum(l) #15

These each also take an optional "key" parameter so that their values will be calculated based on a function of the elements and not based on the elements themselves.

Sort:  

Man, I love lambdas. Ever since they added the arrow notation (basically lambdas) to JavaScript my code looks so much cleaner

If you do front end stuff and like lambda look at Elm. It is ML and what react was based on. Compiles to JavaScript

Sounds pretty cool. I'll have to check it out more! Thanks!

I've heard about it, but to be honest the first time someone described it to me I dismissed it as being a dumb idea. I have no idea what I based that opinion on, so I'm going to go back and read up on it again. Thanks for the recommendation :)

It is all one way flow. You get the state + command. You update the state then sent the new HTML. The virtual dom handles the update.

HTML building is all functions but looks like html.

Coin Marketplace

STEEM 0.17
TRX 0.16
JST 0.030
BTC 59541.21
ETH 2543.02
USDT 1.00
SBD 2.53