with list comprehension
Introduction:
- In Python, you can write a Lambda Function that takes a list as an argument, performs List Comprehension, and returns the result. This is useful for quick and concise operations on lists.
Syntax:
Here's a lambda function that takes a list
numbersas an argument, finds the square of each number in the list, and returns the resulting list:pythonlambda numbers: [x**2 for x in numbers]
Examples:
- Finding the Square of Numbers in a List Using Lambda Function and List Comprehension:
- This example defines a lambda function that takes a list of numbers, finds the square of each number, and returns the resulting list.
Python Program:
pythonsquare_numbers = lambda numbers: [x**2 for x in numbers] numbers = [1, 2, 3, 4, 5] squares = square_numbers(numbers) print(squares)Output:
[1, 4, 9, 16, 25]
- Lambda Function to Return the Length of Strings in a List:
- This example defines a lambda function that takes a list of strings, finds the length of each string, and returns the resulting list.
Python Program:
pythonlen_of_strings = lambda names: [len(x) for x in names] names = ['apple', 'banana', 'fig'] lengths = len_of_strings(names) print(lengths)Output:
[5, 6, 3]
Exercises:
- Convert All Strings in a List to Uppercase:
Define a lambda function that takes a list of strings and returns a list with all strings converted to uppercase.
pythonto_uppercase = lambda strings: [s.upper() for s in strings] names = ['apple', 'banana', 'fig'] uppercase_names = to_uppercase(names) print(uppercase_names) # Output: ['APPLE', 'BANANA', 'FIG']
- Find the Even Numbers in a List:
Define a lambda function that takes a list of numbers and returns a list of only the even numbers.
pythonfind_evens = lambda numbers: [x for x in numbers if x % 2 == 0] numbers = [1, 2, 3, 4, 5, 6] evens = find_evens(numbers) print(evens) # Output: [2, 4, 6]
Summary:
- In this tutorial, we learned how to define a lambda function that performs list comprehension and returns the resulting list. Lambda functions are useful for concise and efficient operations on lists. Practice using lambda functions with list comprehensions to get comfortable with these powerful tools in your Python programs!