Open In App

Python Lambda Functions, Modules, I/O & Memory Handling Interview Question

Last Updated : 26 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python interviews, topics like Lambda functions, Modules, I/O and Memory Handling are commonly asked to test both coding skills and core understanding of the language.

1. What are modules and packages in Python? What is __name__ == "__main__" used for?

  • A module is a .py file containing Python code (functions, classes, variables).
  • A package is a directory containing multiple Python modules and an __init__.py file.

You can import them using:

Python
import math
from datetime import date

The statement:

Python
if __name__ == "__main__":

ensures that code inside this block runs only when the file is executed directly, not when it’s imported as a module.

2. What is a namespace in Python?

A namespace in Python is a system that maps names (like variable or function names) to the objects they refer to. It helps organize and manage names so that there are no conflicts, especially when the same name is used in different parts of a program.

types_namespace-1
Types of namespaces

Types of Namespaces:

  1. Built-in Namespace: Contains all the built-in functions and exceptions, like print(), int(), etc. These are available in every Python program.
  2. Global Namespace: Created when a module is loaded, it contains names defined at the module level.
  3. Local Namespace: Refers to names inside a function or method. Each function call creates a new local namespace.
Python
x = "global"

def outer():
    y = "enclosing"
    
    def inner():
        z = "local"
        print("x:", x)  # global
        print("y:", y)  # enclosing
        print("z:", z)  # local
    inner()

outer()

3. What is Python’s memory model? How does reference counting work?

In Python, everything is an object (numbers, strings, functions, classes, etc.).

Each object has:

  • Type: defines what kind of object it is.
  • Value: the actual data it holds.
  • Reference count: how many variables (or containers) are pointing to it.

Python uses automatic memory management with the help of:

1. Reference Counting: Each object keeps track of how many references point to it. When the count drops to 0, the memory is reclaimed.

Example:

Python
a = [1, 2, 3]
b = a  # Reference count increases
del a  # Decreases by 1

2. Garbage Collection (GC): Python’s gc module handles cyclic references that reference counting can’t clean up.

The memory is managed using heap memory, and objects are tracked using reference counts and generational GC.

4. What does the nonlocal keyword do in Python?

  • The nonlocal keyword in Python is used inside nested functions to indicate that a variable refers to the nearest enclosing scope (not global, not local).
  • Normally, when you assign to a variable inside a function, Python treats it as local to that function. nonlocal allows you to modify a variable from an enclosing (outer) function’s scope instead.

Code Example:

Python
def outer():
    x = 10
    def inner():
        nonlocal x
        x += 5
        print("Inner:", x)
    inner()
    print("Outer:", x)

outer()

Output:

Inner: 15
Outer: 15

Without nonlocal, you'd get an error when trying to assign x inside inner()

5. What is a lambda function?

A lambda function in Python is a small, anonymous (unnamed) function defined using the lambda keyword.

  • It can take any number of arguments but can only contain a single expression.
  • The result of that expression is automatically returned.
  • Often used for short, throwaway functions where using def would be unnecessary.

In the below example, we defined a lambda function(upper) to convert a string to its upper case using upper().

Python
s1 = 'GeeksforGeeks'

upper_case = lambda s: s.upper()

print(upper_case(s1))  # Output: GEEKSFORGEEKS

Output
GEEKSFORGEEKS

6. How are lambda functions used with map(), filter(), and reduce()? Give examples.

Lambda functions are frequently used in combination with Python’s built-in functional programming tools: map, filter, and reduce.

map(function, iterable): Applies a function to every item in an iterable.

Python
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
# Output: [1, 4, 9, 16]
print(squares)

filter(function, iterable): Filters items for which the function returns True.

Python
nums=[1,2,3,4,5]
evens = list(filter(lambda x: x % 2 == 0, nums))
# Output: [2, 4]
print(evens)

(function, iterable): Applies a rolling computation (from functools).

Python
from functools import reduce
nums={2,4,6,2,8,5}
total = reduce(lambda x, y: x + y, nums)
# Output: 25
print(total)

These tools combined with lambda allow you to write highly expressive one-liners.

7. How can lambda functions be used with sorted()? Explain with example.

The sorted() function has a key parameter, which specifies a function to extract the value used for comparison. A lambda function is often passed here (as key parameter) to provide an inline, one-time sorting rule without defining a separate function.

Example 1: Sort by length

Python
words = ["apple", "bat", "banana"]
sorted_words = sorted(words, key=lambda x: len(x))
# Output: ['bat', 'apple', 'banana']
print(sorted_words)

Example 2: Sort list of tuples by second element

Python
pairs = [(1, 3), (2, 1), (4, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
# Output: [(2, 1), (4, 2), (1, 3)]
print(sorted_pairs)

Output
[(2, 1), (4, 2), (1, 3)]

Using lambda with sorted() is useful for customized sorting, often without needing a named function.

8. Can lambda functions return multiple values? Explain with an example.

Lambda functions in Python are limited to a single expression, but that expression can return multiple values—typically as a tuple or a list.

Example:

Python
f = lambda x, y: (x + y, x * y)
result = f(3, 4)
print(result)  # Output: (7, 12)

Output
(7, 12)

Although lambdas don’t use the return keyword, the result of the expression is returned implicitly. You can use lambdas to quickly return combinations of values, such as sum and product, min and max, etc.

Note: if the logic becomes complex or requires multiple steps, a regular def function is more appropriate

9. How does Python handle variable scope and closures?

Python uses the LEGB rule (Local, Enclosing, Global, Built-in) to resolve variables in different scopes.

  • Local (L): Variables defined inside the current function.
  • Enclosing (E): Variables in the enclosing functions (for nested functions).
  • Global (G): Variables declared at the top level of a module or using global.
  • Built-in (B): Names predefined in Python (like len, sum).

A closure occurs when a nested function captures variables from its enclosing scope and remembers their values, even after the outer function has finished execution. Closures are useful for encapsulation, decorators, and callbacks.

Code Example:

Python
def outer(x):
    def inner(y):
        return x + y
    return inner

closure_func = outer(10)
print(closure_func(5))  # Output: 15

Output
15

Here, inner remembers the value of x from outer even after outer has finished. Python stores these variables in the function’s __closure__ attribute.


Explore