Python One Liner Functions
Python one-liner functions are functions that can be written in a single line of code. They are often used to perform simple tasks or expressions without defining a named function. One way to create a one-liner function is to use the lambda keyword which creates an anonymous function that takes some arguments and returns a value. For example:
# A lambda function that returns the square of a number
square = lambda x: x**2
print(square(5)) # 25
# A lambda function that checks if a number is even
is_even = lambda x: x%2 == 0
print(is_even(4)) # True
Another way to create a one-liner function is to use the def keyword with a colon and an expression after it. This creates a named function that returns the value of the expression. For example:
# A one-liner function that returns the sum of two numbers
def add(x, y): return x + y
print(add(3, 4)) # 7
# A one-liner function that reverses a string
def reverse(s): return s[::-1]
print(reverse("hello")) # olleh
Python offers a one-liner function that is called the lambda function. It is also referred to as “Anonymous Function”. The reason is that it doesn’t require def keywords for definition. It can take any number of arguments but only one expression at a time. A good practice is to use it as an expression rather than binding it to a variable.
data = [2,3,7,4,8,10]
is_even = list(map(lambda x:x%2==0, data))
print(is_even)
# output True, False, False, True, True, True
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment