Most Frequently asked Python 3.x Interview Questions

author image Hirely
at 10 Jan, 2025

Question: What are lambda functions in Python?

Answer:

A lambda function in Python is a small, anonymous function defined using the lambda keyword. Unlike a regular function defined with the def keyword, a lambda function can have any number of arguments but can only contain a single expression. The result of the expression is automatically returned by the lambda function.

Lambda functions are often used for short, throwaway functions, especially when the function is required temporarily or when a full function definition is not necessary.

Syntax:

lambda arguments: expression
  • arguments: A comma-separated list of input parameters.
  • expression: A single expression whose value is returned.

Key Characteristics of Lambda Functions:

  1. Anonymous: Lambda functions do not need to be named.
  2. Single Expression: A lambda function can contain only a single expression (no statements like loops or conditionals).
  3. Return Value: The result of the expression is automatically returned without needing to use the return keyword.
  4. Used for Short Functions: Lambdas are typically used when you need a simple function for a short duration, often in places where you don’t want to formally define a function.

Example 1: Basic Lambda Function

# Lambda function to add two numbers
add = lambda x, y: x + y

print(add(2, 3))  # 5

Here, the lambda function lambda x, y: x + y takes two arguments x and y, and returns their sum.

Example 2: Lambda Function Used with sorted()

Lambda functions are often used in functions like sorted(), where you can specify a custom sorting key.

# Sort a list of tuples based on the second element
data = [(1, 3), (2, 2), (4, 1)]
sorted_data = sorted(data, key=lambda x: x[1])

print(sorted_data)  # [(4, 1), (2, 2), (1, 3)]

In this case, the lambda function lambda x: x[1] is used to sort the list of tuples based on the second element.

Example 3: Lambda Function with filter()

Lambda functions are also frequently used with functional programming tools like filter(), map(), and reduce().

# Filter out even numbers using lambda and filter
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(even_numbers)  # [2, 4, 6]

Here, the lambda function lambda x: x % 2 == 0 checks if a number is even and filters the list accordingly.

Example 4: Lambda Function with map()

The map() function applies a lambda function to each item in an iterable (like a list).

# Multiply each number in a list by 2
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))

print(doubled)  # [2, 4, 6, 8]

In this example, the lambda function lambda x: x * 2 is applied to each item in the list numbers.

When to Use Lambda Functions:

  • Short-term functions: When you need a simple function for a short period of time and do not want to formally define it with a def block.
  • Higher-order functions: When passing a function as an argument to higher-order functions like map(), filter(), or sorted().
  • Readability: When the function is simple and you don’t want to clutter the code with a separate function definition.

Limitations of Lambda Functions:

  1. Single expression only: You cannot have multiple expressions or statements in a lambda function (e.g., no loops, conditionals, or multiple operations).
  2. Readability: Overuse of lambda functions, especially for complex expressions, can reduce code readability. In those cases, defining a full function using def might be clearer.

Example: Lambda vs. Regular Function

# Regular function definition
def multiply(x, y):
    return x * y

print(multiply(2, 3))  # 6

# Lambda function
multiply_lambda = lambda x, y: x * y
print(multiply_lambda(2, 3))  # 6

Both functions perform the same operation, but the lambda function is more concise.


Summary:

  • Lambda functions are anonymous functions defined with the lambda keyword.
  • They can have any number of arguments, but only one expression.
  • They are useful for short, simple operations and are commonly used in functional programming tools like map(), filter(), and sorted().
  • While they provide conciseness, excessive use can make code less readable.

Question: What is the purpose of the pass statement in Python?

Answer:

The pass statement in Python is a null operation. It is used when a statement is syntactically required, but you do not want to perform any action or logic. Essentially, pass is a placeholder that allows you to write empty code blocks or define functions, classes, or loops that don’t yet contain code but need to be syntactically correct.

Key Use Cases of pass:

  1. Empty Functions or Methods: Sometimes, you might want to define a function or method without implementing its logic immediately (e.g., during development or for a stub function).

    def my_function():
        pass  # Function defined but does nothing yet
  2. Empty Classes: Similar to functions, you can use pass to create an empty class definition, which can be filled with attributes or methods later.

    class MyClass:
        pass  # Class with no methods or properties yet
  3. Empty Loops or Conditionals: The pass statement is useful when you need a loop or conditional statement for the syntax, but you don’t want it to do anything yet.

    for i in range(5):
        pass  # Loop doesn't do anything, just a placeholder
    
    if some_condition:
        pass  # No action for this condition, but required for the structure
  4. Handling try-except Blocks: pass can be used in an exception handling block when you want to handle an exception but don’t need to take any specific action.

    try:
        risky_operation()
    except ValueError:
        pass  # Ignore the ValueError and do nothing
  5. Abstract Methods: In object-oriented programming, pass can be used in an abstract method or base class that serves as a blueprint, where the implementation is left to subclasses.

    class BaseClass:
        def my_abstract_method(self):
            pass  # No implementation, must be overridden in subclass

Why Use pass?

  • Maintaining Syntax: Python requires that the body of functions, classes, loops, conditionals, and exception blocks contain at least one statement. If you don’t intend to perform any action yet, pass allows you to maintain proper syntax without raising an error.

  • Code Stubs: When working on a large project, you might define empty functions, classes, or loops as placeholders while you work on other parts of the code. pass helps you avoid leaving the code incomplete or throwing errors.

  • Readability: pass makes it clear that you intentionally left a code block empty rather than accidentally leaving it blank or forgetting to add functionality.

Example 1: Empty Function Definition

def do_nothing():
    pass  # No action is performed

Example 2: Empty Class Definition

class Animal:
    pass  # Animal class is defined but has no methods or properties yet

Example 3: Empty Loop

for i in range(10):
    pass  # Loop body does nothing

Summary:

The pass statement in Python is a placeholder that allows you to write syntactically correct code blocks without performing any actual operations. It is commonly used for defining functions, classes, or loops that are not yet implemented or when you want to ignore certain conditions or exceptions in the code.

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