Python

Write an awesome doc for Python. A very nice an practical one extracted from Python official documentation.

View on GitHub

Lambda Expressions

Lambda symbol

[!NOTE]

It is a concept borrowed from functional programming paradigm.

  • In Python lambdas are only a shorthand notation, if you’re too lazy to define a function (ref) you can use lambda function.
  • Keep in mind to NOT expect anything fancy from them.

Lambda Calculus

Lambda functions in Python and other programming languages originates from Lambda Calculus. Here is a formal definition of it + a breakdown:

Lambda Calculus

Syntax

lambda arguments : expression

Examples

def make_incrementor(n):
    return lambda x: x + n
temp = make_incrementor(13) # temp = lambda x: x + 13
print(temp(1)) # lambda 1: 1 + 13 => 14

x = lambda a, b, c: a + b + c
print(x(1, 2, 3)) # lambda 1, 2, 3: 1 + 2 + 3

full_name = lambda first, last: f'{first.strip().capitalize()} {last.strip().title()}'
full_name(' alen ', ' kim ') # Alen Kim

list1 = [1, 2, 3]
list2 = [4, 5, 6]
sum_of_list1_and_list2_elements = list(map(lambda x, y: x + y, list1, list2))
print(sum_of_list1_and_list2_elements)

Normal Function to Lambda Function

Normal func to lambda

Immediately Invoked Function Expression

Debugging

</tbody> </table> ## YouTube/Aparat - [https://youtu.be/QRhJhlMGc8A](https://youtu.be/QRhJhlMGc8A). - [https://aparat.com/v/non5704](https://aparat.com/v/non5704). ## Learn more - [How to Use Python Lambda Functions](https://realpython.com/python-lambda/).
Lambda version Normal Functions

div_zero = lambda x: x / 0
div_zero(2)
Traceback (most recent call last):
    File "", line 1, in 
    File "", line 1, in 
ZeroDivisionError: division by zero
</code>
</pre>
      </td>
      

def div_zero(x): return x / 0
div_zero(2)
Traceback (most recent call last):
    File "", line 1, in 
    File "", line 1, in div_zero
ZeroDivisionError: division by zero
</code>
</pre>
      </td>