My Personal Notes on python's lambda function

#+OPTIONS toc:t

Home

1 Definition: lambda parameter list: returned expression

  • Start with lambda
  • followed by one or more comma separated variables lambda x, y, z
  • a : colon
  • a single expression. This is what will be returned.

1.1 Example lambda functions

lambda x: x**2
#  This could be assigned to a variable if needed:
square = lambda x: x**2

lambda x,y: x + y

mx = lambda x,y: x if x > y else y
print(mx(8,5))
#  But typically we never assign a lambda function to a variable.  We just
#*use the lambda function where the variable would go.

lambda *args: len(args)
#  will tell you how many arguments you have.

1.2 Equivalent functions would look like:

def sqaureme(x):
   return x**2

def add (x,y):
   return x + y

def mx(x,y):
  if x > y:
     return x
  else:
     return y
print(mx(8,5))

2 Comparing traditional functions with lambda functions (syntax)

2.1 Traditional

def f(x):
      return 3*x**2 + 7*x + 1

2.2 Lambda

quadratic = lambda x: 3*x**2 + 7*x + 1
circle = lambda x, y: x**2 + y**2 

In general terms say:

  • lambda followed by zero or more inputs
  • followed by ":"
  • followed by the expression (must be in one line)
  • lamda : "No input lambda, dude!"
  • lambda x: 3*x + 1
  • lambda x, y: (x*y)**0.5 # geometric mean
  • lambda x, y, z: 3/(1/x + 1/y + 1/z) # harmonic mean
  • lambda x1, x2, x3, ... xn: <expression>

3 Example of lambda function with no inputs (as sort keyword)

A very good example of a lambda function with no inputs follows: Taken from Socratica video on the subject https://youtu.be/25ovCm9jKfA

suppose we have a list of names, that are not standardized. we still want to sort the list and print in a nice, standardized way

python_crew = ["Michael Palin", "John Marwood Cleese", "Terry V. Gilliam", "terry jones", "E. Idle"]

Now we want to sort just by last name. If we had a lambda function to standardize this list of names to look at just last names and ignore case (to make the list work as a human would expect)

explaination: so we can extract the last name, and make it all lower case.

  1. split the string by space name.split(" ")
  2. then look at the last item in this split string by looking at the last item which is -1
  3. convert the string to lower case. I think I like to use x because it reminds me of math f(x):m*x + b "f of x maps to mx plus b"

lambda last_name: last_name.split(" ")[-1].lower() lambda x: x.split(" ")[-1].lower()

But, this is bad python style. You should always use varible names that give insight into what the variable represents, in this case last_name

Notice that the variable This lambda function has no inputs, but returns the last[-1] entry of the string input, after it has been standardized to lower case for the times when users are dumb and put block capitals, or capitals in general. This is used typically in sort functions. See python-sort.org for more on using lambda functions with sort.

So for example, combining sort with the lambda function above gives us:

print(f" Here is the list as is: {python_crew} ")

Now sort it using a lambda function for key python_crew.sort(key=lambda x: x.split(" ")[-1].lower())

print(f" Here is the same list, now sorted: {python_crew} ")

In general terms: some_python_list.sort(key=lambda argument: return expression)

myunsortedlist.sort(key=lambda x: x.split(" ")[-1].lower())

3.1 Simple lambda for manipulating two strings as one

This example from Socratica youtube on lambda functions. It also shows built-in string manipulations such as strip which removes leading and trailing white spaces, and title which capitalizes the first character, and all remaining characters are lower case.

full_name = lambda fn, ln: fn.strip().title() + " " + ln.strip().title()

print(full_name("   john", "CLEESE"))
# will print "John Cleese"

4 sort is a list function

First obvious but important statement: sort and sorted work on LISTS !! i.e. they are by definition list functions

If you are wondering how or where does the varialbe x get assigned? Since the sort function is working on a list, the variable x will take on each item of the list, one by one, then sort them

4.1 x takes on each item of the list.

That makes it easier to understand why we can use the varialble 'x' in the lambda function even though it is not defined elsewhere.

4.2 Example if your list has each element itself being a list

This is fairly common on files, where the each line is an element of a list after which you can create a list for each word in the line, by splitting that element. So x[0], and x[1] for example could be the firt two elemeents of the inner list for EACH element of the outer list.

4.3 Examples

given that data is a list as follows: data = [['this', 'is', 'a', 'dead', 'parrot'],['no', 'it', 'is', 'not'], ['it', 'is', 'resting']]

data.sort(key=lambda x:(x[1],x[2])

The variable 'x' above takes on each element of the list it is sorting. the WHOLE element. In the above snippet, s will be a list of strings assigned that are taken from each line of the file info.txt that were stored in the bigger list "data" so x[0], x[1], x[2], etc are the first, second third word on each given line. key=lambda x:(x[2],x[1]) will sort based on the third word in the line, followed by the second word in the line.

data.sort(key=lambda x:(x[0]) gives you this: [['it', 'is', 'resting'], ['no', 'it', 'is', 'not'], ['this', 'is', 'a', 'dead', 'parrot']]

data.sort(key=lambda x:(x[1],x[2]) gives you this: [['this', 'is', 'a', 'dead', 'parrot'], ['it', 'is', 'resting'], ['no', 'it', 'is', 'not']]

data.sort(key=lambda x:(len(x[-1]))) gives you this: [['no', 'it', 'is', 'not'], ['this', 'is', 'a', 'dead', 'parrot'], ['it', 'is', 'resting']]

which was sorting based on the length of the last element of each list.

fibnumbers = ['5', '34 ', '1', '3', '13', '21', '2', '1', '8'] to sort this list numerically, we would have use a key that looks at the converted strings fibnumbers.sort(key=int)

5 functional programming with lambda and built-in functions

First some python built-in functions:

5.1 filter

filter (func, iterable) returns a interator

Filter applies the function to each item of the iterable. If the result of the funciton is true, then it adds that result to the iterator.

For example, find all odd values.

filter (lambda a: a%==1,
        reversed(range(100))) --> iterator.

next(i) --> 99
next(i) --> 97
next(i) --> 95
next(i) --> 93

5.2 map

Map takes a function, and one or more iterables, and also return an iterator. It takes each iterable, and passes each of those to the func. map(func, iterage, ...) --> iterator

An example:

map(lambda x: x**3, range(5)) --> iterator

next(i) -> 0
next(i) -> 1
next(i) -> 8
next(i) -> 27

i = map(lambda x,y: x+y, range(10, range(10,20))

next(i) -> 10
next(i) -> 12

5.3 reduce

5.4 zip

zip(iterable, ...) --> iterator

i = zip(range(10),
        range(10,20),
        range(20,30))

next(i) -> (0, 10, 20)
next(i) -> (1, 11, 21)
next(i) -> (2, 12, 22)
...
next(i) -> (9, 19, 29)

6 functools

functools.partial(func, arg) returns another function.

6.1 Home