Python Partial Function - functools partial() With Examples

What is a Python Partial Function?

Sometimes a function accepts multiple parameters. If there is a situation where we are passing the same parameter to it many times, we can create a python partial function. In the partial function, some of the parameters are fixed. It’s useful in creating a more meaningful function name from an existing function.

How to Create Partial Function in Python?

Python functools partial() function is used to create a partial function. The functools module is for higher order functions. The partial() function syntax is:

It creates a partial function that behaves like calling “func” with fixed positional and keyword arguments. We only need to pass a few of the arguments required to call the underlying function. The other arguments are already provided in the *args and **kwargs.

Python Partial Function Example

Let’s say we have a multiply function like this:

We want to utilize this function to multiply a list of integers with 4 and 5.


We can create a partial function here to multiply an integer with 4 and 5.

Now, the updated code to multiply the list of integers with 4 and 5 will be like this:

We can further reduce the code size using list comprehension.

The output, in this case, will be like this:

Python Partial Function with keyword arguments

If you look at the above output, the positional argument of the partial function is always passed as the first parameter. In this case, it doesn’t matter. But, if the position of the partial function arguments matter, then we can use keyword arguments.



Python partial functions are useful in creating a separate function when we call a function multiple times with some argument being the same all the time.


By admin

Leave a Reply

%d bloggers like this: