{"id":140622,"date":"2023-02-12T06:26:35","date_gmt":"2023-02-12T06:26:35","guid":{"rendered":"https:\/\/ded9.com\/?p=140622"},"modified":"2025-11-20T11:43:59","modified_gmt":"2025-11-20T11:43:59","slug":"how-to-pass-function-as-argument-in-python","status":"publish","type":"post","link":"https:\/\/ded9.com\/de\/how-to-pass-function-as-argument-in-python\/","title":{"rendered":"How to Pass a Function as an Argument in Python"},"content":{"rendered":"<p>Python functions are first-class objects, and for this reason, they provide good functionality to developers, one of which is passing functions as arguments, which we will learn how to do in this article.<\/p>\n<h2><span style=\"font-size: 18pt;\">Pass Function As Argument<\/span><\/h2>\n<p>Suppose we have a list of strings representing the names of fruits:<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; fruits = ['kumquat', 'cherimoya', 'Loquat', 'longan', 'jujube']<\/pre>\n<\/div>\n<p>If we want to sort this list alphabetically, we can pass it to the built-in sort function:<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; sorted(fruits)\r\n\r\n['Loquat', 'cherimoya', 'jujube', 'kumquat', 'longan']<\/pre>\n<\/div>\n<p>As you can see, the sorting is not strictly alphabetical because when <strong style=\"font-style: inherit;\">Python<\/strong> sorts strings, it puts all uppercase letters before all lowercase letters due to the structure of the Unicode and <a href=\"https:\/\/en.wikipedia.org\/wiki\/ASCII\" target=\"_blank\" rel=\"noopener\">ASCII encoding<\/a> systems.\u00a0We can solve this problem by providing a key argument to the built-in sorter function.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; help(sorted)\r\n\r\nsorted(iterable, \/, *, key=None, reverse=False)\r\n\r\n...<\/pre>\n<\/div>\n<p>This key argument should be a function with each item in the fruit list to sort all the elements according to what we want.<\/p>\n<p>In the example above, we can create a function that lowers the letters of any given string so that the sorting process is based on lowercase letters.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; def lowercase(string):\r\n\r\n...\u00a0\u00a0\u00a0\u00a0 return string.lower()\r\n\r\n...<\/pre>\n<\/div>\n<h4>To sort by lowercase strings, we call the sorter with a key argument that points to this lowercase function:<\/h4>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; sorted(fruits, key=lowercase)\r\n\r\n['cherimoya', 'jujube', 'kumquat', 'longan', 'Loquat']<\/pre>\n<\/div>\n<p>This will correctly sort our list of strings alphabetically while preserving the original letter combinations.<\/p>\n<p>Note that when we call the sorter function, we didn&#8217;t put the parentheses (()) after the lowercase letters to call it, and we used the following calling pattern:<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; lowercase('X')\r\n\r\n'x'<\/pre>\n<\/div>\n<p>As you can see, we have not reduced the characters of the string in any way, and we only mentioned the lowercase letters:<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; lowercase\r\n\r\n&lt;function lowercase at 0x7fc8a3fc09d0&gt;<\/pre>\n<\/div>\n<h3><span style=\"font-size: 12pt;\">We passed the lowercase function object to the sorter function via its key argument:<\/span><\/h3>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\">&gt;&gt;&gt; sorted(fruits, key=lowercase)<\/pre>\n<\/div>\n<p>The above example shows that Python allows us to pass functions as arguments to other functions. o that the sorter function can repeatedly call itself on each unique item in the lowercase fruit list, optimizing the sorting process by using the return value as a comparison key. To better understand the issue, let us refer to other models.<\/p>\n<h2><span style=\"font-size: 18pt;\">Another example of assigning a function to a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Variable_(computer_science)\" target=\"_blank\" rel=\"noopener\">variable<\/a> as an object<\/span><\/h2>\n<p>In the following example, a function is assigned to a variable; the procedure is not called in the above allocation process. Instead, the object of the mentioned function is received by shoutout and delivered to the yell variable.<br \/>\nFinally, the input parameter is entered in the yell print command. Receives a pass to the function to print the word hello in capital letters.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\"># Python program to illustrate functions\r\n\r\n# can be treated as objects\r\n\r\ndef shout(text):\r\n\r\nreturn text.upper()\r\n\r\n\r\n\r\n\r\nprint(shout('Hello'))\r\n\r\n\r\n\r\n\r\nyell = shout\r\n\r\n\r\n\r\n\r\nprint(yell('Hello'))<\/pre>\n<\/div>\n<h2><span style=\"font-size: 18pt;\">Higher Order Functions<\/span><\/h2>\n<p>Since functions are objects, we can pass them as arguments to other functions. Functions that can accept other functions as arguments are called higher-order functions. In the following example, a function called greet is created, which receives a function as an argument.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\"># Python program to illustrate functions\r\n\r\n# can be passed as arguments to other functions\r\n\r\ndef shout(text):\r\n\r\nreturn text.upper()\r\n\r\n\r\n\r\n\r\ndef whisper(text):\r\n\r\nreturn text.lower()\r\n\r\n\r\n\r\n\r\ndef greet(func):\r\n\r\n# storing the function in a variable\r\n\r\ngreeting = func(\"Hi, I am created by a function passed as an argument.\")\r\n\r\nprint(greeting)\r\n\r\n\r\n\r\n\r\ngreet(shout)\r\n\r\ngreet(whisper)<\/pre>\n<\/div>\n<p>In the code above, the shout function is defined, which receives a string variable as input, converts it to uppercase letters, and returns it as the function&#8217;s return value.<\/p>\n<p>Next, a second function called whisper is defined, which receives a string variable but converts it to lowercase letters and returns it as the function&#8217;s return value.<\/p>\n<p>The third function is greet, which receives parts as arguments. This function has an idea called func. This variable can receive two parts as arguments. As we mentioned, functions in <strong style=\"font-style: inherit;\">Python<\/strong> are of object type, so the function variable is not a problem in this context. Next, a variable called greeting is defined as one that receives the return value of the function, which is of string type. Next, the print command prints the greeting value.<\/p>\n<p>The last two lines of the above code receive the shout and whisper functions as variables, respectively. As you can see, defining and calling the function in\u00a0<a href=\"https:\/\/ded9.com\/how-to-code-with-python-and-benefit-from-it\/\"><strong style=\"font-style: inherit;\">Python<\/strong> <\/a>is more straightforward than you imagine.<\/p>\n<p>The output of the above code snippet prints the string in uppercase and then lowercase.<\/p>\n<h2><span style=\"font-size: 18pt;\">Wrapper function<\/span><\/h2>\n<p>The wrapper function or decorator allows us to extend the functionality of another function without changing its structure. In the working mechanism of decorators, functions are sent as arguments to another function, and the calling process is done in the wrapper function. Below is an example of a simple decorator.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\"># Defining a decorator\r\n\r\ndef hello_decorator(func):\r\n\r\n\r\n\r\n\r\n# inner1 is a Wrapper function in\r\n\r\n# which the argument is called\r\n\r\n\r\n\r\n\r\n# inner function can access the outer local\r\n\r\n# functions like, in this case, \"func.\"\r\n\r\ndef inner1():\r\n\r\nprint(\"Hello, this is before function execution\")\r\n\r\n\r\n\r\n\r\n# calling the actual function now\r\n\r\n# inside the wrapper function.\r\n\r\nfunc()\r\n\r\n\r\n\r\n\r\nprint(\"This is after function execution\")\r\n\r\n\r\n\r\n\r\nreturn inner1\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# defining a function to be called inside the wrapper\r\n\r\ndef function_to_be_used():\r\n\r\nprint(\"This is inside the function !!\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# passing 'function_to_be_used' inside the\r\n\r\n# decorator to control its behavior\r\n\r\nfunction_to_be_used = hello_decorator(function_to_be_used)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# calling the function\r\n\r\nfunction_to_be_used()<\/pre>\n<\/div>\n<p>The output of the above code snippet is as follows:<\/p>\n<ul>\n<li>Hello, this is before the function execution.<\/li>\n<li>This is inside the function !!<\/li>\n<li>This is after function execution.<\/li>\n<\/ul>\n<h2><span style=\"font-size: 18pt;\">Lambda wrapper function<\/span><\/h2>\n<p>In\u00a0<strong style=\"font-style: inherit;\">Python<\/strong>, an anonymous function means that a function has no name. In <strong style=\"font-style: inherit;\">Python<\/strong>, the def keyword defines normal functions, and the lambda keyword is used to create anonymous functions. This function can take any number of arguments, but can only accept an expression that will be evaluated and returned.<\/p>\n<p>The lambda function can accept another function as an argument. The following example shows an essential lambda function that passes another function as an argument.<\/p>\n<div class=\"wp-block-codemirror-blocks code-block \">\n<pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;lineWrapping&quot;:false,&quot;styleActiveLine&quot;:false,&quot;readOnly&quot;:true,&quot;align&quot;:&quot;&quot;}\"># Defining lambda function\r\n\r\nsquare = lambda x:x * x\r\n\r\n\r\n\r\n\r\n# Defining lambda function\r\n\r\n# and passing function as an argument\r\n\r\ncube = lambda func:func**3\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nprint(\"square of 2 is :\"+str(square(2)))\r\n\r\nprint(\"\\nThe cube of \"+str(square(2))+\" is \" +str(cube(square(2))))<\/pre>\n<\/div>\n<p>The output of the above code snippet is as follows:<\/p>\n<p>Square of 2 is:4<\/p>\n<p>The cube of 4 is 64<\/p>\n<h2>last word<\/h2>\n<p>Python allows us to call functions most simply and send one or more arguments as parameters to other functions. As you have seen, in <strong style=\"font-style: inherit;\">Python,<\/strong> you can pass functions as arguments to other functions; this is possible thanks to the object-oriented nature of functions.<\/p>\n<p>Also, if you pay attention to the first example, this technique allows us to use a particular type of recursive function construction mechanism in an advanced way.<\/p>\n<h2>FAQ<\/h2>\n<div id=\"rank-math-rich-snippet-wrapper\"><div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-1\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Why can I pass a function into another function in Python?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Because in Python, functions are first\u2011class objects \u2014 they can be assigned to variables, passed around, and called just like any other data type.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-2\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">How do I pass a function to another function?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Define a \u201cwrapper\u201d or higher\u2011order function that expects a parameter (say, func), and call it inside \u2014 e.g.: def greet(func): print(func(\"Hello\")) greet(str.upper)<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-3\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Can I pass anonymous (lambda) functions as arguments?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p>Yes \u2014 you can pass a lambda directly, such as: def apply(func, x): return func(x) print(apply(lambda y: y * y, 5)) # 25<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Python functions are first-class objects, and for this reason, they provide good functionality to developers, one of which is passing functions as arguments, which we will learn how to do in this article. Pass Function As Argument Suppose we have a list of strings representing the names of fruits: &gt;&gt;&gt; fruits = [&#8216;kumquat&#8217;, &#8216;cherimoya&#8217;, &#8216;Loquat&#8217;, [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":140623,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[316],"tags":[320],"class_list":["post-140622","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python"],"acf":[],"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/posts\/140622","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/comments?post=140622"}],"version-history":[{"count":3,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/posts\/140622\/revisions"}],"predecessor-version":[{"id":265599,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/posts\/140622\/revisions\/265599"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/media\/140623"}],"wp:attachment":[{"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/media?parent=140622"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/categories?post=140622"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ded9.com\/de\/wp-json\/wp\/v2\/tags?post=140622"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}