Call by value, Call By Reference
-
Everything in python is passed by Reference
Pass by value
Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
Pass by reference
Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
def appendNumber(arr):
arr.append(4)
arr = [1, 2, 3]
appendNumber(arr) #Call by reference
print(arr) #Output: => [1, 2, 3, 4]
Function passing
Passing as | Description |
---|---|
Function used as Object |
|
Function passed as argument to other function |
|
Function as Mutable Objects |
|
Variable no of arguments
def fun(*arg):
for var in arg:
print(var)
return
fun ( 10, 20, 30 )
fun ( 1, 2 )
fun ( 'te', 90 )
Types of Functions
Type | Description |
---|---|
Inner, function inside function |
|
Function Arguments
Type | Description | ||||||
---|---|---|---|---|---|---|---|
Arguments taking default value |
|
||||||
kwarg(Keyword Arguments) |
You can provide different sets of named parameters without having to define them explicitly in the function signature.
|
||||||
Decorator |
a decorator is a powerful design pattern that allows you to modify or
extend the behavior of functions or methods without changing their original code Decorators wrap around a function to enhance or modify its behavior Python builtin decorators: @staticmethod, @classmethod, and @property
|
||||||
enumerate() function |
This is used to iterate over an iterable (Eg: list, tuple, or string). It returns a tuple(index, value of each item)
|
||||||
Lambda / Anonymous function |
Can accept any number of arguments, but can only have a single expression.
Use-case: Require an anonymous function for a short time period.
|
||||||
Generator |
Generator returns an iterator object which can be iterated over.
How yeild works here?
The yield keyword is crucial in creating generators. When yield is encountered:The function's execution is paused A value is returned to the caller The function's state is preserved Execution can resume from where it left off |