WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Python · Basic · question 6 of 100

What is a lambda function? Can you provide an example?

📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

In Python, a lambda function (also known as an anonymous function) is a small, one-line function that can be defined on the fly and used as an argument for other functions. The syntax for a lambda function is simple: you use the lambda keyword followed by a list of arguments (separated by commas), a colon, and then the expression that the function should return. Here is an example of a simple lambda function in Python:

    square = lambda x: x**2

This lambda function takes one argument x and returns its square. You can use this lambda function in the same way as any other function. For example, you could call the function like this:

    result = square(5)
    print(result) # Output: 25

Lambda functions are often used as arguments for higher-order functions such as map(), filter(), and reduce(). For example, here is a simple example of how to use a lambda function with map() to square a list of numbers:

    numbers = [1, 2, 3, 4, 5]
    squared_numbers = list(map(lambda x: x**2, numbers))
    print(squared_numbers) # Output: [1, 4, 9, 16, 25]

In this example, we use the map() function to apply a lambda function to each element of the numbers list. The lambda function takes one argument x and returns its square, and the map() function applies this function to each element of the list. The list() function is used to convert the result into a list.

Lambda functions are particularly useful when you need to define a small, simple function that you don’t want to define separately. They can also make your code more concise and easier to read when used correctly. However, it’s important to use lambda functions judiciously and avoid using them for complex functions that are difficult to read and understand.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Python interview — then scores it.
📞 Practice Python — free 15 min
📕 Buy this interview preparation book: 100 Python questions & answers — PDF + EPUB for $5

All 100 Python questions · All topics