Python Book
🇺🇦 Stand with Ukraine🎓Training Suite
  • Book overview
  • Notes about this book
  • 1. Introduction to Python
    • What is Python
    • Basic syntax
    • Objects in Python
    • Python overview
    • Installation, IDEs etc.
    • ipython
    • Sources for self-learning
  • 2. Strings and numbers
    • Getting help
    • Introspection
    • Basic types
    • None object
    • Numbers
    • Strings
    • Unicode
    • String Formatting
    • Regular expressions
    • Sources for self-learning
  • 3. Containers
    • Data Structures
    • Lists
    • Tuples
    • Dictionaries
    • Sets
    • Conditions
    • Loops
    • Additional modules
    • Sources for self-learning
  • 4. Functions
    • Functions
    • Scopes of visibility
    • Generators
    • Lambdas
    • Type hints
    • Function internals
    • Sources for self-learning
  • 5. Functional Programming
    • Builtins
    • Iterable
    • Iterator
    • Functional Programming
    • Functools
    • Comprehensions
    • Additional modules
    • Sources for self-learning
  • 6. Code Styling
    • Zen of Python
    • Lint
    • PEP 8
    • Modules
    • Packages
    • Sources for self-learning
  • 7. OOP
    • OOP Basics
    • Code design principles
    • Classes
    • Method Resolution Order
    • Magic attributes and methods
    • Super
    • Sources for self-learning
  • 8. Decorators, Exceptions
    • Decorators
    • Exceptions
    • Sources for self-learning
  • 9. Testing
    • Basic Terminology
    • Testing theory
    • Dev unit testing vs QA automated testing
    • Best Practices
    • Doctest
    • Unittest
    • Test Runners
    • Pytest
    • Nose
    • Continuous Integration
  • 10. System Libs
    • Working with files
    • System libraries
    • Subprocess
    • Additional CLI libraries
Powered by GitBook
On this page
  • Example from production
  • Performance of lambda vs regular function

Was this helpful?

Edit on Git
  1. 4. Functions

Lambdas

Anonymous function also known as lambdas after operator which creates them.

Lambda expressions are a way to define a function inline in runtime without a def statement

  • No return, just one single expression

  • def vs lambda – lambda creates and returns function object, def creates and binds the function to the name

  • Not faster

  • They are needed when you want to pass callable object or process something only once.

lambda [arg1 [,arg2,.....argn]]: <expression>
  • Lambdas can take any number of arguments but return just one value in the form of an expression.

  • They cannot contain commands or multiple expressions.

  • An anonymous function cannot be a direct call to print because lambda requires an expression

  • Used a lot in functional programming where you can pass functions to other functions

Why lambda?

  • The lambdas can be used as a function shorthand that allows us to embed a function within the code.

    • key in sorted

🪄 Code:

sorted([1, 2, "a", (3, 4)], key=lambda x: str(x))
sorted([1, 2, 11, 3, "11", "asd", "5"], key=lambda x: f"{x:>10}")

📟 Output:

  • For example, callback handlers are frequently coded as inline lambda expressions embedded directly in a registration call's arguments list. Instead of being define with a def elsewhere in a file and referenced by name

  • Lambdas are also commonly used to code jump tables which are lists or dictionaries of actions to be performed on demand.

🪄 Code:

f = lambda x, y: x + y 
f(2, 6)

📟 Output:

8

🪄 Code:

list(map(lambda x: x**2, range(5)))

📟 Output:

[0, 1, 4, 9, 16]
def power_n(n): 
    import math 
    return lambda x: math.pow(x, n) 
print(power_n(3)(3))
squared = power_n(4)
print(squared(5))

Example from production

conversions = {
            "ram"                    : lambda a, v, m, o: memory.normalizeRam(v),
            "logical_ram"            : lambda a, v, m, o: memory.normalizeRam(v),
            "processor_type"         : lambda a, v, m, o: None,
            "num_processors"         : lambda a, v, m, o: None,
            "num_logical_processors" : lambda a, v, m, o: None,
            "uptime"                 : convertUptime,
            "uptimeSeconds"          : intConvert,
    }

Performance of lambda vs regular function

The same.

🪄 Code:

def f1():
    return len([x for x in range(10000)])

f2 = lambda: len([x for x in range(10000)])

%timeit f1()
%timeit f2()

📟 Output:

680 µs ± 37.4 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
649 µs ± 5.79 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

This is because lambda is syntax sugar and in the end almost the same code is being constructed

🪄 Code:

import dis
dis.dis(f1)

📟 Output:

  2           0 LOAD_GLOBAL              0 (len)
              3 LOAD_CONST               1 (<code object <listcomp> at 0x103e14c90, file "<ipython-input-67-9c2575e1edb3>", line 2>)
              6 LOAD_CONST               2 ('f1.<locals>.<listcomp>')
              9 MAKE_FUNCTION            0
             12 LOAD_GLOBAL              1 (range)
             15 LOAD_CONST               3 (10000)
             18 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             21 GET_ITER
             22 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             25 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             28 RETURN_VALUE

🪄 Code:

dis.dis(f2)

📟 Output:

  4           0 LOAD_GLOBAL              0 (len)
              3 LOAD_CONST               1 (<code object <listcomp> at 0x103e149c0, file "<ipython-input-67-9c2575e1edb3>", line 4>)
              6 LOAD_CONST               2 ('<lambda>.<locals>.<listcomp>')
              9 MAKE_FUNCTION            0
             12 LOAD_GLOBAL              1 (range)
             15 LOAD_CONST               3 (10000)
             18 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             21 GET_ITER
             22 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             25 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             28 RETURN_VALUE
PreviousGeneratorsNextType hints

Last updated 2 years ago

Was this helpful?