Lamda Function And List of Useful function With Additional Question

M3-R5.1 · Chapter 6: Functions · 11 min read

LAMBDA FUNCTON: A lambda function is a small anonymous function defined using the lambda keyword. It can take any number of arguments but has only one expression. It's often used for short functions that are used once or in a limited scope, such as in map(), filter(), or sorted().

                                                                        OR

A lambda function is a small anonymous function—basically a one-liner shorthand for defining simple functions without a formal def statement.

Syntax :     

                 lambda arguments: expression

When to use lambda:

  • When the function is simple and short.
  • When you don't want to formally define a function using def.

Note: lambda functions are limited to a single expression and can't contain statements or annotations. If your function is complex, use a def instead.

Example: Basic usage      

dnum = lambda x: x * 2

print(dnum(4))      

                  Output: 8

square = lambda x: x ** 2

print(square(5))       

              # Output: 25         

add = lambda x, y: x + y

print(add(3, 7)) 

                             # Output: 10

Explanation:

  • lambda x: x * 2 creates a function that takes one argument x and returns x * 2.
  • dnum(4) calls the lambda function with 4 and returns 8.

Example:      

sum =lambda arg1,arg2: arg1+arg2;

print(" Value of Total:",sum(10,20))

print(" Value of Total:",sum(20,20))

sum =lambda arg1,arg2: arg1+arg2;

r=sum(10,20)

r1=sum(20,20)

print(" Value of Total:",r)

print(" Value of Total:",r1)

 NOTE : We can use lambda functions wherever you need a short function—like with map(), filter(), or sorted().

Q: write a python program to find the even number from list using lamda function

# a quick use with filter():

L1 = [1, 2, 3, 4, 5]

evnum = list(filter(lambda x: x % 2 == 0, L1))

print(evnum)        # Output: [2, 4]

Q: write a python program to print the square a list of numbers using lamda function

# Here Using map()

numbers = [1, 2, 3, 4]

squared = list(map(lambda x: x**2, numbers))

print(squared)           # Output: [1, 4, 9, 16]

Q: write a python program to find the strings which start with a in a list using lamda function.      #Filtering Strings that Start with "a"

List1 = ["apple", "banana", "apricot", "cherry"]

List2= list(filter(lambda x: x.startswith("a"), List1))

print(List2)               # Output: ['apple', 'apricot']

List of some usefull fuctions:

Function Name

Use for

Library function

input()

Is built-in functions , used to obtain information from the user

eval()

It converts a string containing a valid expression to an object

Print()

It is use to display textual information to the user

String Functions

count()

Returns the number of times a specified value occurs in a string

find()

Is used to locate the position of the given substring within the string . it returns -1 if not find the substring

rfind()

Searches the string for a specified value and returns the last position of where it was found.

capitalize()

Returns a copy of the string with only it first character capitalized

title()

Convert the first character of each word to uppercase

lower()

It converts all the uppercase letters in a string to lowercase

upper()

It returns the exact copy of the string with all letters in uppercase

swapcase()

It returns a copy of the string with lowercase letters turned into uppercase and vice-versa

islower()

It returns true if the string is in lowercase and false otherwise

isupper()

It returns true if the string is in uppercase and false otherwise

istitle()

It checks whether the string is title cased. And returns true if string is properly title cased, otherwise false

replace(old,new)

It replaces all occurrences of old substring in a string with the new substring

strip()

It removes whitespaces from start and end of string

lstrip()

It removes all the leading(left side) whitespaces in the string

rstrip()

It removes default whitespaces  character from the right of string.

split()

It returns a list of the words of a string . it assumes that words are separated by whitespace, which can be either spaces, tabs or newline characters

partition()

Splits the string at the first occurrence of separators and returns the string in three parts

join()

Takes a list of strings and joins them together into a single string.

isspace()

It returns true if the string contains only whitespace characters and false otherwise

isalpha()

It returns true if the string contains only letters otherwise false

isdigit()

It returns true if the string contains only digits otherwise false

isalnum()

It checks whether string consists of only alphanumeric charactes.

startswith()

It check whether that stirng starts with a particular string and returns true if the string starts with the specified string

endswith()

It check whether that string end with a particular string and returns true if the string endwith the specified string

encode() and decode()

This method are used to transform string dat to and from a specified character encoding as input , these accept and encoding name such as “ascii” ,” utf-8”

String: Slicing

Is use to extracting part of the string

Membership

Membership operator “in” returns if a character exists in the given string, false otherwise

Numeric Functions

max()

It returns the largest of its parameters.

min()

It returns the smallest of its parameters.

pow()

Return the 1st value of raise to power of 2nd value

round()

It return the round s of a floating point number to the nearest integral number and return the results still as float

int()

It constructs an integer numbers from an integer literals , float or string literals

random()

It is part of the random package which returns a floating point value

ceil()

It returns the smallest whole number greater than or equal to a number

floor()

Returns the largest integer less than or equal to a given integer

sqrt()

Return non negative square root of a number

Date & Time Functions

This module named datetime to work with dates and times

Q: WAP to print the power of a number using function

def pof(x):

    y=x*x

    return y

a=int(input("Plz enter the value"))

z=pof(a)

print("the power of a nuber is=", z)

Q: WAP to print the table  of a number using function

def tab(a):

    for i in range (1,11):

        f=a*i

        print(a,"x",i,"=",f)

n=int(input("Plz enter teh value"))

tab(n)

Q: WAPto print the area of circle using function and radius is input by user

def cir():

    r=int(input("Plz enter the radius"))

    for i in range (1,11):

        ar=3.14*r*r

        return ar

area=cir()

print("\n area of circle is=",area)

def pat():

    for i in range (1,6):

        for j in range (i,6):

            print(j,end="")

        print()

pat()

Q: Python Program to Find the Sum of Natural Numbers Using Recursion

def rsum(n):

    if n <= 1:

        return n

    else:

        return n + rsum(n-1)

num = int(input("Enter a number: "))

sum=rsum(num)

print("The sum is",sum)

Method:2

def rsum(n):

   if n <= 1:

       return n

   else:

       return n + rsum(n-1)

num = int(input("Plz enter the number:"))

if num < 0:

   print("Enter a positive number")

else:

   sum=rsum(num)

   print("The sum is",sum)

Q:Program to count number of digit in a number Using Recursive Function

def count(n):

    if(n == 0):

        return 0

    return count(int(n/10)) + 1

num = int(input("Plz enter the number"))

totnum=count(num)

print("Total digit in a number is=",totnum)

Program to count number of digit in a number Using Function

 def cd(n):

    count = 0

    while n != 0:

        n = n //10

        count += 1

    return count

n = int(input("Please enter a number"))

totnum=cd(n)

print("Number of digits :" ,totnum)

Q:Program to print sum of digit of a number Using Function

def sumdigit(n):

    if n< 10:

        return n

    else:

        return n%10 + sumdigit(n//10)

num = int(input("Enter number: "))

print("Sum of digit is" ,sumdigit(num))

Q:Program to print sum of digit of a number Using recursive Function

def sumdigit( n ):

                if n == 0:

                                return 0

                return (n % 10 + sumdigit(int(n / 10)))

num = int(input("Enter the number whose sum of digits you want:"))

result = sumdigit(num)

print("Sum of digits of number",num,"is", result,"Using Recursion")

Q: Program to print Length of the String using Recursion

def length(str):

    if str == "":

        return 0

    return 1 + length(str[1:])

str = input("plz enter the string")

print("length of", str, "is", length(str))

#Using the Loop  https://prepinsta.com/top-100-codes/

def length(str):

    i = 0

    while str != "":

        i += 1

        str = str[1:]

    return i

str = input("plz enter the string")

print("length of", str, "is", length(str))

Q: Program to find the power of a number using recursion

def power(a, b):

    if b != 0:

        return a * power(a, b - 1)

    else:

        return 1

a = int(input("plze enter the First Number"))

b = int(input("plze enter the Second Number"))

print(a, "to the power", b, "is", power(a, b))

Q: Python program to print the Fibonacci series using recursion:

def fibo(n):

    if n<=1:

        return n

    else:

        return(fibo(n-1)+fibo(n-2))

num=int(input(" Enter the number for fibonacci series: "))

for i in range(num):

    print(fibo(i)," ", end=" ")