Beginner 5 min

Scope and lifetime

Scope decides where a name can be used, and lifetime describes how long a value remains available.

How it works

Say where the name was introduced before looking for it. A local name is available in its own function. Returning the value is like handing it to the caller, which can use a new name for it. That is why something can leave a scope in one place and remain useful elsewhere.

Walk through an example

A variable created inside a function is normally accessible by name only there. The function can return the value, and a caller can keep it under a different name.

What to watch for

A name going out of scope does not necessarily destroy its value. Other references to the same object can keep it available.

Check your understanding

Can the caller still use the list?

See the example and explanation
Worked example
Given A function creates a list and returns it to a caller.
Answer Yes.

The local name goes away, but the caller now has a reference to the returned list.

Open practice problem
Next lessonEvaluate a machine learning model