Essential Python 3.x Interview Questions

author image Hirely
at 10 Jan, 2025

Question: How does Python handle variable scope and namespaces?

Answer:

In Python, variable scope and namespaces refer to how and where variables are stored, accessed, and modified within a program. Understanding the concepts of scope and namespaces is essential to writing clean and efficient code and avoiding issues like variable name conflicts or unintended modifications.


1. What is a Namespace?

A namespace in Python refers to a container that holds a collection of variable names (keys) and their corresponding objects (values). Each variable name in Python is a reference to an object in memory, and a namespace ensures that each name refers to the correct object.

There are several types of namespaces in Python, including:

  • Local Namespace: This refers to the namespace inside a function or method. Variables defined inside a function are in the local namespace of that function.
  • Enclosing Namespace: This refers to the namespace of any enclosing functions, like closures. If a function is defined inside another function, the inner function has access to variables from the outer function’s namespace.
  • Global Namespace: This refers to the namespace at the level of the main program. Variables defined at the top level of a module are in the global namespace of that module.
  • Built-in Namespace: This contains Python’s built-in functions and exceptions, like print(), len(), and ValueError. These are always available for use throughout the program.

Each namespace is independent of the others, meaning that variables in one namespace do not directly affect variables in another namespace.


2. What is Variable Scope?

The scope of a variable in Python refers to the region of the code where the variable is accessible. The scope determines where a variable can be used, read, or modified. Python uses the LEGB rule to resolve variable names, which stands for:

  • Local: The innermost scope, which includes variables defined inside a function or method.
  • Enclosing: The scope of any enclosing function, for example, when one function is nested inside another.
  • Global: The scope of variables defined at the top level of a module or script.
  • Built-in: The outermost scope, containing names like print(), len(), and exceptions.

Python will search for a variable in the order of LEGB—starting with the local scope, then moving to the enclosing scope, then the global scope, and finally the built-in scope. If a variable is not found in any of these scopes, a NameError will occur.


3. The LEGB Rule:

Python searches for variables based on the LEGB rule. Let’s break this down:

Local Scope (L)

  • Variables defined inside a function or a block of code.
  • These variables are only accessible inside the function or block.

Example:

def func():
    x = 10  # Local variable
    print(x)

func()  # Output: 10
# print(x)  # This will raise a NameError because 'x' is local to func

Enclosing Scope (E)

  • This scope is relevant when you have nested functions (functions inside functions).
  • Variables from the outer (enclosing) function are accessible from the inner function.

Example:

def outer():
    x = 5  # Variable in enclosing scope
    def inner():
        print(x)  # Accessing variable from the enclosing function
    inner()

outer()  # Output: 5

Global Scope (G)

  • Variables defined at the top level of a script or module.
  • These variables are accessible throughout the module.

Example:

x = 20  # Global variable

def func():
    print(x)  # Accessing the global variable

func()  # Output: 20

Built-in Scope (B)

  • This scope includes Python’s built-in functions, exceptions, and other objects like print(), len(), range(), and others.
  • These names are always available throughout the program.

Example:

print(len("Hello"))  # len() is a built-in function

4. Modifying Variables in Different Scopes

Python distinguishes between local, global, and nonlocal variables when you want to modify variables from different scopes.

Local Variables:

Variables defined inside a function or method are local to that function. They can be modified directly within the function.

Global Variables:

To modify a global variable inside a function, you must use the global keyword.

Example (Global Variable):

x = 10  # Global variable

def modify_global():
    global x  # Declare x as global
    x = 20  # Modify global variable

modify_global()
print(x)  # Output: 20

Enclosing (Nonlocal) Variables:

If you want to modify a variable in the enclosing function’s scope (but not in the global scope), you use the nonlocal keyword. This is typically used in nested functions.

Example (Enclosing Variable):

def outer():
    x = 5  # Enclosing variable
    def inner():
        nonlocal x  # Declare x as nonlocal (from the enclosing scope)
        x = 10  # Modify the enclosing variable
    inner()
    print(x)  # Output: 10

outer()

5. Example with LEGB Rule

Consider this example with all scopes involved:

x = 50  # Global variable

def outer():
    x = 10  # Enclosing variable
    def inner():
        x = 5  # Local variable
        print(x)  # This will print the local x

    inner()
    print(x)  # This will print the enclosing x

outer()
print(x)  # This will print the global x

Output:

5  # Printed from the inner function (local x)
10  # Printed from the outer function (enclosing x)
50  # Printed from the global scope (global x)

6. The globals() and locals() Functions

  • globals(): Returns a dictionary of the global namespace (variables at the module level).
  • locals(): Returns a dictionary of the local namespace (variables inside a function).

Example:

x = 100  # Global variable

def test():
    y = 200  # Local variable
    print(globals())  # Prints the global namespace (including 'x')
    print(locals())  # Prints the local namespace (including 'y')

test()

Summary:

  1. Namespace is a container where variable names are mapped to objects. Python has four main namespaces: local, enclosing, global, and built-in.
  2. Scope refers to the region where a variable is accessible. Python resolves variable names using the LEGB rule (Local -> Enclosing -> Global -> Built-in).
  3. To modify variables from different scopes, Python uses the global keyword (for global scope) and nonlocal keyword (for enclosing scopes).
  4. Functions like globals() and locals() can be used to access the current namespace.

By understanding variable scope and namespaces in Python, you can write cleaner, more efficient, and less error-prone code.

Question: What is the difference between del and remove() in Python?

Answer:

Both del and remove() are used to remove elements in Python, but they work in different ways and have distinct use cases. Here’s a breakdown of the differences:


1. del Statement

The del statement is used to delete an object or a variable entirely. It can be used to remove elements from lists, delete variables, or even delete entire slices of a list.

Key Points about del:

  • Used for deleting objects: You can use del to remove variables, list elements, or even dictionary keys.
  • Works by index: When used with a list, del removes the item at a specific index.
  • Can delete entire slices: It can be used to delete multiple elements in a list using slicing.

Example 1: Deleting a Variable

x = 10
del x  # Deletes the variable x
# print(x)  # This will raise a NameError because x no longer exists

Example 2: Deleting an Element by Index from a List

my_list = [10, 20, 30, 40, 50]
del my_list[2]  # Removes the element at index 2 (value 30)
print(my_list)  # Output: [10, 20, 40, 50]

Example 3: Deleting a Slice of a List

my_list = [10, 20, 30, 40, 50]
del my_list[1:3]  # Removes elements at index 1 and 2 (values 20 and 30)
print(my_list)  # Output: [10, 40, 50]

Important Notes:

  • The del statement does not return any value.
  • It raises an error if the specified index is out of range or if the variable doesn’t exist.

2. remove() Method

The remove() method is a list method that removes the first occurrence of a specific value from a list. If the value is not found, it raises a ValueError.

Key Points about remove():

  • Used for removing by value: It removes the first occurrence of the specified value in the list.
  • Modifies the list in place: The list is modified, and the method does not return a new list.
  • Raises an error if the value is not found: If the specified value is not present in the list, it raises a ValueError.

Example 1: Removing an Element by Value

my_list = [10, 20, 30, 40, 50]
my_list.remove(30)  # Removes the first occurrence of the value 30
print(my_list)  # Output: [10, 20, 40, 50]

Example 2: Value Not Found (Raises ValueError)

my_list = [10, 20, 30, 40, 50]
# my_list.remove(60)  # This will raise a ValueError because 60 is not in the list

Key Differences:

Aspectdelremove()
Type of RemovalRemoves by index or deletes the entire object.Removes by value (first occurrence).
Syntaxdel list[index] or del variablelist.remove(value)
Return ValueDoes not return anything (raises error on failure).Does not return anything (raises ValueError if the value is not found).
Error HandlingRaises an IndexError if the index is out of range.Raises a ValueError if the value is not found.
Used WithLists, dictionaries, or variables.Only with lists.
Can Remove Multiple ElementsCan delete slices (e.g., del list[start:end]).Can only remove one element at a time (the first occurrence of the value).

Summary:

  • del is a Python statement that is used to remove an element at a specific index from a list, delete a variable, or delete an entire slice of a list.
  • remove() is a list method that removes the first occurrence of a specific value from the list. If the value is not present, it raises a ValueError.

Use del when you want to remove an element by index or delete an entire variable, and use remove() when you need to remove an element by its value.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as Python 3.x interview questions, Python 3.x interview experiences, and details about various Python 3.x job positions. [Click here](https://www.aihirely.com/tag/Python 3.x) to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now