Scope and lambda

Local names, functions as values, lambda.

Names created inside a function are local: they are not visible outside, and they disappear after the function returns. A function can read global names, but an assignment inside the function creates a new local name:

x = 10

def change():
    x = 5
    return x

change()
print(x)   # 10

The global x did not change: inside the function there was its own, local x. The global keyword lets you change a global variable, but good code avoids it. A function that gets its data through parameters and hands it back with return is clearer and easier to test.

If a function first reads a name and then assigns a value to it, Python treats the name as local throughout the whole body. Reading before the assignment gives UnboundLocalError. The error looks odd, but the reason is simple: an assignment anywhere in the function makes the name local.

Functions in Python are ordinary values. You can put them in a variable or a list, or pass them to another function:

def shout(text):
    return text.upper()

action = shout
print(action("hi"))   # HI

For short one-off functions there is lambda: lambda x: x * 2 is a nameless function made of one expression. Most often it is passed as a sorting key: sorted(words, key=lambda w: len(w)). If a lambda does not fit on a short line, declare an ordinary function with def and a clear name.

Practice

  1. A local name

    What does the program print?

    x = 10
    
    def f():
        x = 5
        return x
    
    f()
    print(x)
    
  2. What a lambda is

    What does the expression lambda x: x * 2 do?

    • Creates a function that doubles its argument
    • Doubles the variable x right away
    • Declares a variable called lambda
    • Creates a list of doubled numbers
  3. By the last letter

    Write a function by_last_letter(words) that returns a new list of words sorted by the last letter of each word.