Add Number to All Elements in List

Tags: Lambda, Lists

Write a Python lambda function that takes a list and a number as arguments and returns a new list with the number added to all elements. The function should accept a list of numbers and a single number, and return a list of numbers.

Example 1:

Input: [1, 2, 3], 5
Output: [6, 7, 8]

Example 2:

Input: [10, 20, 30], -10
Output: [0, 10, 20]

You can use a list comprehension or the map function in combination with a lambda function to create the new list.

# Define the lambda function
add_number_to_list = lambda lst, n: list(map(lambda x: x + n, lst))

# Test the function
print(add_number_to_list([1, 2, 3], 5))  # Output: [6, 7, 8]
print(add_number_to_list([10, 20, 30], -10))  # Output: [0, 10, 20]

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!