{"id":120704,"date":"2020-11-15T17:04:07","date_gmt":"2020-11-15T17:04:07","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=16827"},"modified":"2020-11-15T17:04:07","modified_gmt":"2020-11-15T17:04:07","slug":"python-function-call-inside-list-comprehension","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/11\/15\/python-function-call-inside-list-comprehension\/","title":{"rendered":"Python Function Call Inside List Comprehension"},"content":{"rendered":"<p><strong>Question<\/strong>: Is it possible to call a function inside a <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\" target=\"_blank\" rel=\"noreferrer noopener\">list comprehension<\/a> statement?<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><strong>Background<\/strong>: List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]<\/code>.<\/p>\n<ul>\n<li><strong>Expression: <\/strong>What to do with each list element?<\/li>\n<li><strong>Context: <\/strong>What elements to select? The context consists of an arbitrary number of <code>for<\/code> and <code>if<\/code> statements.<\/li>\n<\/ul>\n<p>For example, the code <code>[x**2 for x in range(3)]<\/code> creates the list of square numbers <code>[0, 1, 4]<\/code> with the help of the expression <code>x**2<\/code>. <\/p>\n<p><strong>Related article:<\/strong> <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"List Comprehension in Python \u2014 A Helpful Illustrated Guide\">List Comprehension in Python &#8212; A Helpful Illustrated Guide<\/a><\/p>\n<hr class=\"wp-block-separator\"\/>\n<p><em><strong>So, can you use a function with or without return value as an expression inside a list comprehension?<\/strong><\/em><\/p>\n<p class=\"has-pale-cyan-blue-background-color has-background\"><strong>Answer<\/strong>: You can use any expression inside the list comprehension, including functions and methods. An expression can be an integer <code>42<\/code>, a numerical computation <code>2+2 (=4)<\/code>, or even a function call <code>np.sum(x)<\/code> on any iterable <code>x<\/code>. Any function without return value, returns <code>None<\/code> per default. That&#8217;s why you can even call functions with side effects within a list comprehension statement.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[print('hi') for _ in range(10)] '''\nhi\nhi\nhi\nhi\nhi\nhi\nhi\nhi\nhi\nhi '''<\/pre>\n<p>You use the throw-away underscore <code>_<\/code> because you want to execute the same function ten times. If you want to print the first 10 numbers to the shell, the following code does the trick:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[print(i) for i in range(10)] '''\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9 '''\n<\/pre>\n<p>Let&#8217;s have a look at the content of the list you just created: <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">lst = [print(i) for i in range(10)]\nprint(lst)\n# [None, None, None, None, None, None, None, None, None, None]<\/pre>\n<p>The list contains ten <code>None<\/code> values because the return value of the <code><a href=\"https:\/\/blog.finxter.com\/the-separator-and-end-arguments-of-the-python-print-function\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Python Print Function [And Its SECRET Separator &amp; End Arguments]\">print()<\/a><\/code> function is <code>None<\/code>. The side effect of executing the print function within the list comprehension statement is that the first ten values from 0 to 9 appear on your standard output. <\/p>\n<h3>Walrus Operator<\/h3>\n<p>Python 3.8 has introduced the <a href=\"https:\/\/blog.finxter.com\/python-3-8-walrus-operator-assignment-expression\/\" title=\"Python 3.8 Walrus Operator (Assignment Expression)\" target=\"_blank\" rel=\"noreferrer noopener\">walrus operator<\/a>, also known as the <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0572\/\" target=\"_blank\" rel=\"noreferrer noopener\">assignment expression<\/a>. This operator is useful if executing a certain function has side effects that you don&#8217;t want. For example, if you have a string creation method inside the list comprehension statement, conditioned by some filtering criterion in the if suffix. Without the walrus operator, Python would execute this same routine multiple times&#8212;even though this is highly redundant. You can avoid this redundancy by assigning it to a variable <code>s<\/code> once using the walrus operator and reusing this exact variable in the expression. <\/p>\n<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import random def get_random_string(): return f'sss {random.randrange(0, 100)}' # Goal: Print all random strings that contain 42 # WRONG\nlst = [get_random_string() for _ in range(1000) if '42' in get_random_string()]\nprint(lst)\n# ['sss 74', 'sss 13', 'sss 76', 'sss 13', 'sss 92', 'sss 96', 'sss 27', 'sss 43', 'sss 80'] # CORRECT\nlst = [s for _ in range(1000) if '42' in (s := get_random_string())]\nprint(lst)\n# ['sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42', 'sss 42']\n<\/pre>\n<p>With the walrus operator <code>s := get_random_string()<\/code>, you store the result of the function call in the variable <code>s<\/code> and retrieve it inside the expression part of the list comprehension. All of this happens inside the list comprehension statement. <\/p>\n<p><strong><em>I teach these concepts in my exclusive FINXTER email academy&#8212;join us, it&#8217;s free!<\/em><\/strong><\/p>\n<h2> Related Video: List Comprehension<\/h2>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" title=\"A Simple Introduction to List Comprehension in Python\" width=\"1400\" height=\"788\" src=\"https:\/\/www.youtube.com\/embed\/9qsq2Vf48W8?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen><\/iframe><\/div>\n<\/div>\n<\/figure>\n<p>The post <a href=\"https:\/\/blog.finxter.com\/python-function-call-inside-list-comprehension\/\" target=\"_blank\" rel=\"noopener noreferrer\">Python Function Call Inside List Comprehension<\/a> first appeared on <a href=\"https:\/\/blog.finxter.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Finxter<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Question: Is it possible to call a function inside a list comprehension statement? Background: List comprehension is a compact way of creating lists. The simple formula is [expression + context]. Expression: What to do with each list element? Context: What elements to select? The context consists of an arbitrary number of for and if statements. [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-120704","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/120704","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=120704"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/120704\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=120704"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=120704"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=120704"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}