Functions in Python
This article explains functions in Python.
YouTube Video
Functions in Python
Functions in Python are an essential feature for defining reusable blocks of code, allowing you to organize and simplify your program by calling them as needed. Using functions can improve code readability and adhere to the DRY principle (Don't Repeat Yourself, avoid writing the same code multiple times).
Defining Functions
Functions are defined using the def
keyword. The basic syntax is as follows:.
1def function_name(arg1, arg2, ..., argN):
2 """docstring (A brief description of the function)"""
3 processing
4 return return_value
For example, to define a function that adds two numbers, you would write:.
1def add(x, y):
2 """A function that adds two numbers and returns the result"""
3 return x + y
Calling Functions
A defined function can be called and used as follows:.
1result = add(3, 4)
2print(result) # Output: 7
Components of a Function
-
Function Name
- The name of the function, used when calling it.
-
Arguments (Parameters)
- The variable names that receive the data passed at the time of the call. You can define zero or more arguments.
-
Documentation String (Docstring)
- A string that describes the purpose and usage of the function. Optional.
-
Function Body
- An indented block where the instructions executed by the function are written.
-
Return Value
- The value returned to the caller using the
return
statement. Ifreturn
is omitted,None
is returned by default.
- The value returned to the caller using the
Types of Arguments
In Python, there are several types of arguments.
- Positional Arguments
- The usual way to pass arguments to a function.
- Default Arguments
- Assign default values to arguments so they can be omitted when calling the function.
1def greet(name, message="Hello"):
2 print(f"{message}, {name}")
3
4greet("Alice") # "Hello, Alice"
5greet("Bob", "Good morning") # "Good morning, Bob"
- Variable-length Arguments
args
receives multiple positional arguments as a tuple, andkwargs
receives them as a dictionary.
1def func(*args, **kwargs):
2 print("args:", args)
3 print("kwargs:", kwargs)
4
5func(1, 2, 3, a=4, b=5)
6# Output:
7# args: (1, 2, 3)
8# kwargs: {'a': 4, 'b': 5}
By using functions correctly, you can write Python programs more effectively and efficiently.
Lambda Functions in Python
In Python, lambda
functions are used to define anonymous, concise functions. Unlike functions defined with the normal def
keyword, lambda
allows you to create short, single-line functions. Here, we will explain lambda
functions in Python in detail.
Basics of lambda
Functions
lambda
functions, also called anonymous functions, are used to define temporary functions that have no name, as the name suggests. The basic syntax is as follows:.
1lambda arguments: expression
arguments
- Specifies the arguments of a function. Multiple arguments can be specified, separated by commas.
expression
- An expression evaluated based on the arguments. The result of the expression becomes the return value of the function.
For example, the following code defines and executes a lambda
function that adds two numbers.
1add = lambda x, y: x + y
2print(add(5, 3)) # Output: 8
In this example, lambda x, y: x + y
is a lambda
function that takes two arguments, x
and y
, and returns their sum.
Use Cases of lambda
Functions
lambda
functions are useful for situations where you need to define a simple function on the spot. They are particularly common in the following cases:.
-
When Passed as Arguments to Functions
- It is useful in higher-order functions (functions that take other functions as arguments) when passing short, temporary functions.
-
When Specifying Keys for Sorting Lists
- They are handy for specifying sorting criteria (keys) in functions like
sort()
orsorted()
.
- They are handy for specifying sorting criteria (keys) in functions like
Example Usage in Higher-Order Functions
Typical examples of higher-order functions include map()
, filter()
, and reduce()
. These functions take other functions as arguments and apply them to sequences like lists.
1numbers = [1, 2, 3, 4, 5]
2squared = list(map(lambda x: x ** 2, numbers))
3print(squared) # Output: [1, 4, 9, 16, 25]
In this example, a lambda
function is passed to the map()
function to square each number in a list.
Examples of using list sorting
The lambda
function can sometimes be used to specify a custom key when sorting a list. For example, the following code sorts a list of tuples based on the second element.
1pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
2pairs.sort(key=lambda pair: pair[1])
3print(pairs)
4# Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
In this example, a lambda
function is used to sort the tuples based on their second element (a string).
filter()
and lambda
The filter()
function is used to filter elements in a list (or other iterable) based on a given condition.
1numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
2even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
3print(even_numbers) # Output: [2, 4, 6, 8]
In this example, even numbers in a list are filtered to create a new list.
lambda
and reduce()
The reduce()
function is used to reduce a list into a single value. It can be implemented easily using a lambda
function.
1from functools import reduce
2
3numbers = [1, 2, 3, 4, 5]
4product = reduce(lambda x, y: x * y, numbers)
5print(product) # Output: 120
In this example, all elements in the list are multiplied together to produce a result.
Avoid using complex lambda
functions
The advantage of lambda
functions is their brevity, but they become harder to read when used for implementing complex logic. Therefore, it is appropriate to use them for simple operations that can be expressed in a single line. For complex operations, defining a function with def
is more readable and maintainable.
For example, you should avoid using complex lambda
functions like the one below.
1# Complex and hard-to-read lambda function
2complex_func = lambda x, y: (x * 2 + y) if x > y else (x + y * 2)
In this case, it is better to use a function defined with def
, as shown below.
1def complex_func(x, y):
2 if x > y:
3 return x * 2 + y
4 else:
5 return x + y * 2
Conclusion
Python's lambda
functions are a convenient tool for defining temporary, short functions. They are often used in higher-order functions or list operations to concisely define specific conditions. However, lambda
functions should be limited to simple tasks, with def
functions preferred for complex logic.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.