I1 · Python Programming for AI

Scope and Lambda Functions

Scope is the part of a program where a name can be used. Variables created inside a function are local to it and disappear when it ends; variables created at the top level are global. A lambda is a small anonymous function written in one expression, such as lambda x: x * 2, often passed to functions like sorted().

8 min Intermediate · Sublevel Beginner Jump to the activity

What you need: The earlier topics of this module.

Definition

Why can't a function see a variable created inside another function?

Scope is the part of a program where a name can be used. Variables created inside a function are local to it and disappear when it ends; variables created at the top level are global. A lambda is a small anonymous function written in one expression, such as lambda x: x * 2, often passed to functions like sorted().

In simple words

Each function call gets its own private notebook. What it writes there is gone when it finishes, and it can't scribble in another function's notebook. A lambda is a function so short you don't bother naming it: sorted(students, key=lambda s: s[1]) means 'sort by the second item'.

Overview

  • Scope is the region of a program where a name can be seen and used.
  • Python looks up names in LEGB order: Local, Enclosing, Global, Built-in.
  • Variables created inside a function are local and disappear when it returns.
  • global and nonlocal let a function change a variable in an outer scope, but should be used rarely.
  • A lambda is a small anonymous function written as one expression: lambda x: x * 2.
  • Lambdas are most useful as short keys for sorted(), min(), max(), map() and filter().

Why it matters

Scope prevents functions from accidentally changing each other's variables, which keeps large programs safe. Lambdas are used constantly for sorting and for quick transformations in data code.

Key terms

Scope
The region of a program where a name can be used.
Local variable
A name created inside a function, existing only while it runs.
Global variable
A name created at the top level of a file, visible throughout it.
LEGB rule
Python looks up names in Local, Enclosing, Global, then Built-in scope.
Lambda
A small anonymous function written in one expression.
Higher-order function
A function that takes or returns another function, such as sorted() with key=.

Types

Python has four kinds of scope, checked in LEGB order, and one special kind of function, the lambda. Each is explained below.

1. Local scope

Names created inside a function, including its parameters.

  • How it works: They exist only while the function runs; two functions can use the same local name without affecting each other.
  • Example: Inside def area(r): pi_r = 3.14 * r, the name pi_r cannot be seen outside area.
  • When to use it: Use local variables for almost everything; they keep functions independent and safe.

2. Enclosing (nonlocal) scope

Names in an outer function, seen by a function defined inside it.

  • How it works: An inner function can read them; to change one it must declare nonlocal name; this is how closures remember values.
  • Example: def counter(): count = 0; def step(): nonlocal count; count += 1; return count; return step.
  • When to use it: Use it for closures and decorators, where an inner function needs remembered state.

3. Global scope

Names created at the top level of a file (module).

  • How it works: Any function can read a global; to assign to it inside a function you must declare global name, otherwise Python creates a new local.
  • Example: PASS_MARK = 33 at the top of a file is read by every grading function.
  • When to use it: Use globals for constants; avoid changing them from functions, which makes bugs hard to trace.

4. Built-in scope

Names Python provides everywhere, such as len, print, sum, max and True.

  • How it works: Python checks it last; if you create a variable named sum or list, you hide the built-in in that scope.
  • Example: sum = 0 followed by sum([1, 2]) fails with TypeError because sum is now an integer.
  • When to use it: Avoid reusing built-in names for your variables.

5. Lambda (anonymous) functions

One-expression functions written with lambda parameters: expression.

  • How it works: The expression's value is returned automatically; a lambda cannot contain statements such as loops or assignments.
  • Example: sorted(students, key=lambda s: s["marks"], reverse=True) ranks students by marks.
  • When to use it: Use them for short throwaway functions passed to other functions; use def for anything reused or longer.

Explained in detail

Where names live

Each function call gets its own private space for names. A variable created inside a function is local: it appears when the function starts and disappears when it ends, and nothing outside can see it. This is a feature, not a limitation. It means you can use a common name such as total inside ten different functions without them interfering with each other. When Python meets a name, it searches in a fixed order, known as LEGB: the Local scope of the current function, then any Enclosing function, then the Global scope of the file, then the Built-in names such as len and print.

Reading and changing globals

A function can read a global variable freely, but if it assigns to that name, Python treats the name as local throughout the function. That is why count = count + 1 inside a function raises UnboundLocalError when count is global. The global keyword lets a function change a global, but it is usually a sign of fragile design: the function now depends on hidden outside state. The cleaner approach is to pass the value in as a parameter and return the new value.

Lambdas

A lambda is a function without a name, limited to a single expression: lambda x: x * 2 does the same as def double(x): return x * 2. Lambdas are handy where a small function is needed only once, especially as the key argument to sorted(), min() and max(). For example, sorted(students, key=lambda s: s[1], reverse=True) sorts a list of (name, mark) tuples by mark, highest first. If a lambda grows complicated, give it a proper def and a name; readability matters more than brevity.

TaskWith a lambda
Sort words by lengthsorted(words, key=lambda w: len(w))
Find the student with the top markmax(marks.items(), key=lambda kv: kv[1])
Keep only even numberslist(filter(lambda n: n % 2 == 0, nums))
Square every numberlist(map(lambda n: n * n, nums))

For the last two, a comprehension is usually clearer: [n for n in nums if n % 2 == 0] and [n * n for n in nums]. Treating functions as values that can be passed around, which is what key=, map() and filter() do, is an idea called functional programming. You will see it again in pandas, where df.apply(some_function) runs a function on every row or column.

How it works

  • Local: created inside a function, visible only there.
  • Global: created at the top level, readable inside functions.
  • Assigning to a name inside a function creates a new local variable, even if a global has the same name.
  • Prefer passing values in and returning results out over changing globals.

In code

A local variable that shadows a global, and lambdas used to sort records.

scope_and_lambda.py
count = 10            # global

def add_five():
    count = 5         # a new local variable, not the global
    return count

print("Inside the function:", add_five())
print("Global is unchanged:", count)

students = [("Aarav", 72), ("Meera", 91), ("Kabir", 64)]
by_marks = sorted(students, key=lambda s: s[1], reverse=True)
print("By marks:", by_marks)
print("By name length:", sorted(students, key=lambda s: len(s[0])))

double = lambda x: x * 2
print("double(21) =", double(21))

Output

Inside the function: 5
Global is unchanged: 10
By marks: [('Meera', 91), ('Aarav', 72), ('Kabir', 64)]
By name length: [('Aarav', 72), ('Meera', 91), ('Kabir', 64)]
double(21) = 42

Try it yourself

Which value is used?

x = 1 at the top level. Is each x local or global?

  • print(x) at the top level after calling f()

  • x inside def f(): x = 5; return x

  • x inside def g(): return x + 1 (no assignment)

  • A parameter: def h(x): return x * 2

Common mistakes

  • Expecting a function to change a global by assigning to it.
  • Using a local variable after the function has ended.
  • Writing long lambdas. If it needs more than one expression, use def.

Check yourself

Question 1

1. A variable created inside a function is…

Question 2

2. sorted([3, -5, 1], key=lambda n: abs(n)) is…

Question 3

3. lambda x: x + 1 is…

Summary

  • Local variables live inside a function; globals live at the top level.
  • Assigning inside a function creates a local; pass values instead of changing globals.
  • lambda makes a tiny function, ideal as a sort key.

Finished reading?

Sources: W3Schools: Python Lambda