Docsity

Python Function Arguments: A Comprehensive Guide, Study notes of Computer science

Toggle sidebar
bg1
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:
• Default argument
• Keyword arguments (named arguments)
• Positional arguments
• Arbitrary arguments (variable-length arguments *args and **kwargs)
Arbitrary Keyword Arguments
In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
# Python program to illustrate
# *args for variable number of arguments
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c

Partial preview of the text

Download Python Function Arguments: A Comprehensive Guide and more Study notes Computer science in PDF only on Docsity!

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:

  • Default argument
  • Keyword arguments (named arguments)
  • Positional arguments
  • Arbitrary arguments (variable-length arguments *args and **kwargs) Arbitrary Keyword Arguments In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of arguments to a function using special symbols. There are two special symbols:
  • *args in Python (Non-Keyword Arguments)
  • **kwargs in Python (Keyword Arguments) Example 1: Variable length non-keywords argument _# Python program to illustrate

*args for variable number of arguments_

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

Method to print a greeting message_

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

*kwargs for variable number of keyword arguments_

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).

  • *args (Non-keyword arguments): Packs multiple positional arguments into a tuple.
  • ****kwargs (Keyword arguments):** Packs multiple keyword arguments into a dictionary. 1. Packing with args The * operator allows us to pass multiple arguments to a function and pack them into a tuple. Example Code: def sample(args): print("Packed arguments:", args) sample(1, 2, 3, 4, "geeks for geeks") Output Packed arguments: (1, 2, 3, 4, 'geeks for geeks') 2. Packing with kwargs ** operator is used to collect multiple keyword arguments into a dictionary. Code def sample(kwargs): print("Packed keyword arguments:", kwargs)

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:

  • *args collects (1, 2, 3) as a tuple.
  • **kwargs collects name="geeks for geeks" and age=30 into a dictionary. Difference between Packing and Unpacking Features Packing Unpacking Definition Collects multiple values into a single variable (tuple, list, or dictionary). Extracts values from a collection (tuple, list, or dictionary) into individual variables. Operator Used
  • (for tuples/lists), ** (for dictionaries).
  • (for lists/tuples), ** (for dictionaries). Purpose Allows functions to accept a variable number of arguments. Allows passing values dynamically to functions or variables. Data Structure Combine multiple values into a single entity (tuple or dictionary). Extracts multiple values from a single entity into separate variables.

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,

  1. into args. func([1, 2, 3, 4]) → Unpacks [1, 2, 3, 4] as separate arguments. Storage Format Tuple (args) or Dictionary (**kwargs). Individual variables or function arguments. Docstring The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice. The below syntax can be used to print out the docstring of a function. Syntax: print(function_name.doc) Example: Adding Docstring to the function _# A simple Python function to check

whether x is even or odd_

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:

  • Built-in function
  • User-defined function
  • Lambda functions [Anonymous Functions in Python]
  • Recursive functions Anonymous Functions in Python In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. # Python code to illustrate the cube of a number using lambda function

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

  • lambda: The keyword to define the function.
  • arguments: A comma-separated list of input parameters (like in a regular function).
  • expression: A single expression that is evaluated and returned. Let’s see some of the practical uses of the Python lambda function. lambda with Condition Checking A lambda function can include conditions using if statements. Example: # Example: Check if a number is positive, negative, or zero n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero" print(n(5)) print(n(-3)) print(n(0)) Output Positive Negative Zero

li = [lambda arg=x: arg * 10 for x in range(1, 5)] for i in li: print(i()) Output 10 20 30 40 Explanation:

  • The lambda function squares each element.
  • The list comprehension iterates through li and applies the lambda to each element.
  • This is ideal for applying transformations to datasets in data preprocessing or manipulation tasks. Lambda with if-else lambda functions can incorporate conditional logic directly, allowing us to handle simple decision making within the function. Example: # Example: Check if a number is even or odd check = lambda x: "Even" if x % 2 == 0 else "Odd" print(check(4)) print(check(7)) Output Even Odd Explanation:
  • The lambda checks if a number is divisible by 2 (x % 2 == 0).
  • Returns “Even” for true and “Odd” otherwise.
  • This approach is useful for labeling or categorizing values based on simple conditions. Lambda with Multiple Statements

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:

  • The lambda function performs both addition and multiplication and returns a tuple with both results.
  • This is useful for scenarios where multiple calculations need to be performed and returned together. Lambda functions can be used along with built-in functions like filter(), map() and reduce(). Using lambda with filter() The filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let’s see a simple example of filter() function in python: Example: # Example: Filter even numbers from a list n = [1, 2, 3, 4, 5, 6] even = filter( lambda x: x % 2 == 0, n) print(list(even)) Output [2, 4, 6] Explanation:
  • The lambda function checks if a number is even (x % 2 == 0).
  • filter() applies this condition to each element in nums.

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:

  • The filter() function extracts even numbers from numbers.
  • The map() function doubles each filtered number.
  • The combination simplifies complex data pipelines. filter() in python – FAQs What does the filter() function do? The filter() function in Python filters elements from an iterable (like a list) based on a function (or None for truthy values). It returns an iterator that yields those elements for which the function returns True. How does reduce() and filter() work in Python?
  • filter(): Filters elements from an iterable based on a function.
  • reduce(): Applies a function to the items of an iterable, cumulatively, from left to right, so as to reduce the iterable to a single value. Both functions are part of Python’s functools module (Python 3.x) and can be used together to filter and then reduce data if needed. How to filter a list in Python? To filter a list in Python, you can use a list comprehension or the filter() function along with a lambda function or a defined function. Using list comprehension: # Example using list comprehension a= [1, 2, 3, 4, 5, 6, 7, 8, 9] b= [num for num in a if num % 2 == 0] print(b) # Output: [2, 4, 6, 8] Using lambda with map() The map() function is used to apply a given function to every item of an iterable , such as a list or tuple, and returns a map object (which is an iterator). Let’s start with a simple example of using map() to convert a list of strings into a list of integers. s = ['1', '2', '3', '4'] res = map(int, s) print(list(res)) Output [1, 2, 3, 4] Explanation: Here, we used the built-in int function to convert each string in the list s into an integer. The map() function takes care of applying int() to every element Syntax of the map() function The syntax for the map() function is as follows: map(function, iterable) Parameter:
  • function: The function we want to apply to every element of the iterable.
  • iterable: The iterable whose elements we want to process. Note: We can also pass multiple iterables if our function accepts multiple arguments. Converting map object to a list By default, the map() function returns a map object , which is an iterator. In many cases, we will need to convert this iterator to a list to work with the results directly.

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:

  • The lambda function doubles each number.
  • map() iterates through a and applies the transformation. Using lambda with reduce()