




















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















































Types of Python Function Arguments Python supports various types of arguments that can be passed at the time of the function call. In Python, we have the following function argument types in Python:
def myFun(*argv): for arg in argv: print(arg) myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') Output: Hello Welcome to GeeksforGeeks Example 2: Python program to illustrate *args with a first extra argument. def fun(arg1, *argv): print("First argument :", arg1) for arg in argv: print("Argument *argv :", arg) fun('Hello', 'Welcome', 'to', 'GeeksforGeeks') Output First argument : Hello
Argument *argv : Welcome Argument *argv : to Argument argv : GeeksforGeeks Example: def fun(args): for arg in args: print(arg) # Calling the function with multiple arguments fun(1, 2, 3, 4, 5) Output 1 2 3 4 5 **Python def keyword example with kwargs In Python, kwargs is used to pass a variable number of keyword arguments to a function. The ** syntax collects the keyword arguments into a dictionary, where the keys are the argument names and the values are the corresponding argument values. This allows the function to accept any number of named (keyword) arguments. def fun(kwargs): for k, val in kwargs.items(): print(f" { k } : { val } ") # Calling the function with keyword arguments fun(name="Alice", age=30, city="New York") Output name: Alice age: 30 city: New York
# Constructor to initialize the person's name and age def init(self, name, age): self.name = name # Set the name attribute self.age = age _# Set the age attribute
def greet(self): print(f"Name - { self.name } and Age - { self.age } .") # Create an instance of the Person class p1 = Person("Alice", 30) # Call the greet method to display the greeting message p1.greet() Output Name - Alice and Age - 30. 2: Variable length keyword arguments _# Python program to illustrate
def myFun(**kwargs): for key, value in kwargs.items(): print(" %s == %s " % (key, value)) # Driver code myFun(first='Geeks', mid='for', last='Geeks') Output: first == Geeks mid == for last == Geeks **Using both *args and kwargs We can use both *args and **kwargs in the same function to accept a mix of positional and keyword arguments.
Example: def fun(*args, **kwargs): print("Positional arguments:", args) print("Keyword arguments:", kwargs) fun(1, 2, 3, a=4, b=5) Output Positional arguments: (1, 2, 3) Keyword arguments: {'a': 4, 'b': 5} Packing and Unpacking Arguments in Python Python provides the concept of packing and unpacking arguments, which allows us to handle variable-length arguments efficiently. This feature is useful when we don’t know beforehand how many arguments will be passed to a function. Packing Arguments Packing allows multiple values to be combined into a single parameter using * (for tuples/lists) and ** (for dictionaries).
Packing and Unpacking Together We can use Packing and Unpacking in same function. Example def together(*args, **kwargs): print("Positional:", args) print("Keyword arguments:", kwargs) together(1, 2, 3, name="geeks for geeks", age=30) Output Positional: (1, 2, 3) Keyword arguments: {'name': 'geeks for geeks', 'age': 30} Explanation:
Features Packing Unpacking Example in function definition def func(args): (packs multiple positional arguments into a tuple) def func(kwargs): (packs multiple keyword arguments into a dictionary) func(list_var) (unpacks elements from a list/tuple) func(**dict_var) (unpacks key-value pairs from a dictionary) Example inf unction call func(1, 2, 3, 4) → Packs (1, 2, 3,
def evenOdd(x): """Function to check if the number is even or odd""" if (x % 2 == 0): print("even") else : print("odd") # Driver code to call the function print(evenOdd.doc) Output: Function to check if the number is even or odd
_args_* is used when you want to pass a variable number of arguments to a function without explicitly specifying each argument in a list. It allows for flexibility and simplicity when defining functions that may take an unknown number of arguments. def sum_values(*args): total = sum(args) return total result = sum_values(1, 2, 3, 4, 5) print(result) # Output: 15 Python Function within Functions A function that is defined inside another function is known as the inner function or nested function. Nested functions can access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function. # Python program to demonstrate accessing of variables of nested functions def f1(): s = 'I love GeeksforGeeks' def f2(): print(s) f2() # Driver's code f1() Output: I love GeeksforGeeks What are the 4 types of Functions in Python? The main types of functions in Python are:
def cube(x): return xxx cube_v2 = lambda x : xxx print(cube(7)) print(cube_v2(7)) Output: 343 343 s1 = 'GeeksforGeeks' s2 = lambda func: func.upper() print(s2(s1)) Output GEEKSFORGEEKS Python Lambda Function Syntax Syntax: lambda arguments : expression
li = [lambda arg=x: arg * 10 for x in range(1, 5)] for i in li: print(i()) Output 10 20 30 40 Explanation:
Lambda functions do not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function. Example: # Example: Perform addition and multiplication in a single line calc = lambda x, y: (x + y, x * y) res = calc(3, 4) print(res) Output (7, 12) Explanation:
print(list(b)) Output [2, 4, 6] Here, the lambda function replaces even and directly defines the condition x % 2 == 0 inline. Combining filter() with Other Functions We can combine filter() with other Python functions like map() or use it in a pipeline to process data efficiently. Example: Filtering and Transforming Data a = [1, 2, 3, 4, 5, 6] # First, filter even numbers b = filter( lambda x: x % 2 == 0, a) # Then, double the filtered numbers c = map( lambda x: x * 2, b) print(list(c)) Output [4, 8, 12] Explanation:
We can use map() with multiple iterables if the function we are applying takes more than one argument. Example: In this example, map() takes two iterables ( a and b ) and applies the lambda function to add corresponding elements from both lists. a = [1, 2, 3] b = [4, 5, 6] res = map( lambda x, y: x + y, a, b) print(list(res)) Output [5, 7, 9] Examples of map() function Converting to uppercase This example shows how we can use map() to convert a list of strings to uppercase. fruits = ['apple', 'banana', 'cherry'] res = map(str.upper, fruits) print(list(res)) Output ['APPLE', 'BANANA', 'CHERRY'] Explanation: The str.upper method is applied to each element in the list fruits using map(). The result is a list of uppercase versions of each fruit name. Extracting first character from strings In this example, we use map() to extract the first character from each string in a list. words = ['apple', 'banana', 'cherry'] res = map( lambda s: s[0], words) print(list(res)) Output ['a', 'b', 'c'] Explanation: The lambda function s: s[0] extracts the first character from each string in the list words. map() applies this lambda function to every element, resulting in a list of the first characters of each word. Removing whitespaces from strings
In this example, We can use map() to remove leading and trailing whitespaces from each string in a list. s = [' hello ', ' world ', ' python '] res = map(str.strip, s) print(list(res)) Output ['hello', 'world', 'python'] Explanation: The str.strip method removes leading and trailing whitespaces from each string in the list strings. The map() function applies str.strip to each element and returning a list of trimmed strings. Calculate fahrenheit from celsius In this example, we use map() to convert a list of temperatures from Celsius to Fahrenheit. celsius = [0, 20, 37, 100] fahrenheit = map( lambda c: (c * 9/5) + 32, celsius) print(list(fahrenheit)) Output [32.0, 68.0, 98.6, 212.0] The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a new list is returned which contains all the lambda-modified items returned by that function for each item. Example: # Example: Double each number in a list a = [1, 2, 3, 4] b = map( lambda x: x * 2, a) print(list(b)) Output [2, 4, 6, 8] Explanation: