Anonymous Functions and Lambda

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Anonymous Functions in Python are called lambda functions. They are a way to create functions without a name. They are useful for creating short functions that are only used once.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/lambda_functions("`Lambda Functions`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/BasicConceptsGroup -.-> python/python_shell("`Python Shell`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/variables_data_types -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/booleans -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/for_loops -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/lists -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/tuples -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/dictionaries -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/function_definition -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/lambda_functions -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/importing_modules -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/standard_libraries -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/data_collections -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/python_shell -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} python/build_in_functions -.-> lab-132731{{"`Anonymous Functions and Lambda`"}} end

List Sorting Revisited

Lists can be sorted in-place. Using the sort method.

s = [10,1,7,3]
s.sort() ## s = [1,3,7,10]

You can sort in reverse order.

s = [10,1,7,3]
s.sort(reverse=True) ## s = [10,7,3,1]

It seems simple enough. However, how do we sort a list of dicts?

[{'name': 'AA', 'price': 32.2, 'shares': 100},
{'name': 'IBM', 'price': 91.1, 'shares': 50},
{'name': 'CAT', 'price': 83.44, 'shares': 150},
{'name': 'MSFT', 'price': 51.23, 'shares': 200},
{'name': 'GE', 'price': 40.37, 'shares': 95},
{'name': 'MSFT', 'price': 65.1, 'shares': 50},
{'name': 'IBM', 'price': 70.44, 'shares': 100}]

By what criteria?

You can guide the sorting by using a key function. The key function is a function that receives the dictionary and returns the value of interest for sorting.

portfolio = [
    {'name': 'AA', 'price': 32.2, 'shares': 100},
    {'name': 'IBM', 'price': 91.1, 'shares': 50},
    {'name': 'CAT', 'price': 83.44, 'shares': 150},
    {'name': 'MSFT', 'price': 51.23, 'shares': 200},
    {'name': 'GE', 'price': 40.37, 'shares': 95},
    {'name': 'MSFT', 'price': 65.1, 'shares': 50},
    {'name': 'IBM', 'price': 70.44, 'shares': 100}
]

def stock_name(s):
    return s['name']

portfolio.sort(key=stock_name)

Here's the result.

## Check how the dictionaries are sorted by the `name` key
[
  {'name': 'AA', 'price': 32.2, 'shares': 100},
  {'name': 'CAT', 'price': 83.44, 'shares': 150},
  {'name': 'GE', 'price': 40.37, 'shares': 95},
  {'name': 'IBM', 'price': 91.1, 'shares': 50},
  {'name': 'IBM', 'price': 70.44, 'shares': 100},
  {'name': 'MSFT', 'price': 51.23, 'shares': 200},
  {'name': 'MSFT', 'price': 65.1, 'shares': 50}
]

Callback Functions

In the above example, the key function is an example of a callback function. The sort() method "calls back" to a function you supply. Callback functions are often short one-line functions that are only used for that one operation. Programmers often ask for a short-cut for specifying this extra processing.

Lambda: Anonymous Functions

Use a lambda instead of creating the function. In our previous sorting example.

portfolio.sort(key=lambda s: s['name'])

This creates an unnamed function that evaluates a single expression. The above code is much shorter than the initial code.

def stock_name(s):
    return s['name']

portfolio.sort(key=stock_name)

## vs lambda
portfolio.sort(key=lambda s: s['name'])

Using lambda

  • lambda is highly restricted.
  • Only a single expression is allowed.
  • No statements like if, while, etc.
  • Most common use is with functions like sort().

Read some stock portfolio data and convert it into a list:

>>> import report
>>> portfolio = list(report.read_portfolio('portfolio.csv'))
>>> for s in portfolio:
        print(s)

Stock('AA', 100, 32.2)
Stock('IBM', 50, 91.1)
Stock('CAT', 150, 83.44)
Stock('MSFT', 200, 51.23)
Stock('GE', 95, 40.37)
Stock('MSFT', 50, 65.1)
Stock('IBM', 100, 70.44)
>>>

Exercise 7.5: Sorting on a field

Try the following statements which sort the portfolio data alphabetically by stock name.

>>> def stock_name(s):
       return s.name

>>> portfolio.sort(key=stock_name)
>>> for s in portfolio:
           print(s)

... inspect the result ...
>>>

In this part, the stock_name() function extracts the name of a stock from a single entry in the portfolio list. sort() uses the result of this function to do the comparison.

Exercise 7.6: Sorting on a field with lambda

Try sorting the portfolio according the number of shares using a lambda expression:

>>> portfolio.sort(key=lambda s: s.shares)
>>> for s in portfolio:
        print(s)

... inspect the result ...
>>>

Try sorting the portfolio according to the price of each stock

>>> portfolio.sort(key=lambda s: s.price)
>>> for s in portfolio:
        print(s)

... inspect the result ...
>>>

Note: lambda is a useful shortcut because it allows you to define a special processing function directly in the call to sort() as opposed to having to define a separate function first.

Summary

Congratulations! You have completed the Anonymous Functions and Lambda lab. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like