Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

Lambda Functions/shaare/PlNZLA

  • python
  • python

Lambda Functions

  • Python functions defined with def allow multiple statements, clear naming, and support for docstrings, making them ideal for complex or reusable logic.
  • In many cases, you need a simple, single-expression function to pass directly to another function without the ceremony of a full definition.
  • The lambda keyword lets you create small, anonymous functions inline, avoiding the verbosity of a def for trivial operations.
  • These one-line functions are particularly handy when you want to supply custom behavior to built-in higher-order functions without polluting your namespace with one-off function names.

Syntax of a lambda Function

  • A lambda function follows the exact pattern: lambda <arguments>: <expression>, where the expression result is implicitly returned.
  • The lambda keyword introduces the function, <arguments> lists its parameters, and a colon separates them from the single expression body.
  • You cannot include multiple statements, loops, or traditional if/else blocks: only a single expression or a ternary expression.
  • Compared to a def function, a lambda is nameless and concise, making it ideal for inline usage where defining a named function would be overkill.
square = lambda x: x * x
print(square(5))

print((lambda a, b: a + b)(3, 4))

Custom Sorting with sorted()

  • The built-in sorted() function accepts an optional key parameter, which should be a function that returns a comparison key for each element.
  • Using a lambda for the key argument lets you define the sorting logic inline without a separate function definition.
  • This approach keeps your code concise and focused, especially when the key logic is a simple attribute extraction or computation.
  • When you need more complex sorting logic, you can still fall back to a named def function for clarity.
services = [("web-app", 3), ("database", 1), ("cache", 5), ("api-gateway", 2)]

print(f"Default sort: {sorted(services)}")

def get_replica_count(svc_tuple):
    return svc_tuple[1]

print(f"Sorting by replica count - standard function: {sorted(services, key=get_replica_count)}")
print(f"Sorting by replica count - lambda function: {sorted(services, key=lambda svc: svc[1])}")

Transforming Data with map()

  • The map(function, iterable) built-in applies a given function to each item in an iterable, producing an iterator of results.
  • Using a lambda with map lets you specify simple transformations inline without an extra function definition.
  • Although list comprehensions are often preferred for readability, map with a lambda can be concise when you already need an iterator or want to emphasize the function-application nature.
  • Remember that map returns a lazy iterator; convert it to a list if you need to access all results at once.
my_numbers = [1, 2, 3, 4]
print(list(map(lambda num: num * 2, my_numbers)))

ports = [80, 443, 8080, 22]
port_descriptions = list(map(lambda port: f"Port {port} is open", ports))

print(port_descriptions)

Filtering Data with filter()

  • The filter(function, iterable) built-in yields only those items for which the function returns True.
  • A lambda in filter is perfect for inline tests, such as checking attributes or simple conditions.
  • As with map, filter returns an iterator, so wrap it in list() to evaluate immediately if needed.
  • While list comprehensions can express filtering more idiomatically in modern Python, filter remains a clear demonstration of higher-order function usage.
ports = [80, 443, 8080, 22, 5432]

privileged_ports = list(filter(lambda port: port < 1024, ports))
print(privileged_ports)

privileged_comprehension = [port for port in ports if port < 1024]
print(privileged_comprehension)
3 months ago Permalien
cluster icon
  • Functions: return vs yield : Functions: return vs yield Regular functions execute immediately, run to completion, and return a single value (or None). Generator functions retur...
  • Working with JSON files : Working with JSON files JSON is the standard format for data exchange in web services and cloud APIs. Python’s built-in json module provides function...
  • Enhancing Functions: Decorators : Enhancing Functions: Decorators A decorator is a callable that takes another function, adds behaviour before and/or after it runs, and returns a new ...
  • Dictionaries : Dictionaries (dict) Dictionaries are mutable, insertion-ordered collections of key-value pairs. Keys must be unique and immutable; values can be of an...
  • Editable Installs with pyproject.toml : Editable Installs with pyproject.toml The Python interpreter doesn't automatically know about our project's structure. The modern and most robust solu...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli