{"id":10853,"date":"2022-09-25T05:36:28","date_gmt":"2022-09-25T00:06:28","guid":{"rendered":"http:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/"},"modified":"2022-09-25T05:36:28","modified_gmt":"2022-09-25T00:06:28","slug":"solved-python-list-comprehension-execution-order-duplicate","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/","title":{"rendered":"[Solved] Python List comprehension execution order [duplicate]"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-57044328\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"57044328\" data-parentid=\"57023018\" data-score=\"2\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<h1>Order of elements<\/h1>\n<p>The <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/www.python.org\/dev\/peps\/pep-0202\/\">PEP 202<\/a> is not very&#8230; comprehensive, but you can found some information in the <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/reference\/expressions.html#displays-for-lists-sets-and-dictionaries\">Python Language Reference<\/a>:<\/p>\n<blockquote>\n<p>The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached.<br \/>\n  [&#8230;]<br \/>\n  The iterable expression in the leftmost for clause is evaluated directly in the enclosing scope and then passed as an argument to the implictly nested scope.<\/p>\n<\/blockquote>\n<p>Therefore list comprehension proceeds <code>for<\/code> blocks from left to right.<\/p>\n<p>But in your case, you have two list comprehensions having each one block:<\/p>\n<ul>\n<li>outer list comprehension: do something for each <code>row<\/code> in <code>matrix<\/code>;<\/li>\n<li>inner list comprehension(do something with <code>row<\/code>): do something else for each <code>x<\/code> in <code>row<\/code>.<\/li>\n<\/ul>\n<p>That&#8217;s why your list comprehension is better read from right to left.<br \/>\nIt is easier to see with a function:<\/p>\n<pre><code>&gt;&gt;&gt; def square_elements(row): return [x**2 for x in row] # inner\n...\n&gt;&gt;&gt; matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n&gt;&gt;&gt; [square_elements(row) for row in matrix] # outer\n[[1, 4, 9], [16, 25, 36], [49, 64, 81]]\n<\/code><\/pre>\n<p>Consider now a two blocks list comprehension:<\/p>\n<pre><code>&gt;&gt;&gt; [x**2 for row in matrix for x in row]\n[1, 4, 9, 16, 25, 36, 49, 64, 81]\n<\/code><\/pre>\n<p>You see the left to right order. In the first case, you have: <em>do something for each <code>row<\/code> in <code>matrix<\/code>, and that something is: do something else for each <code>x<\/code> in <code>row<\/code><\/em>. In the second case it is: <em>do something for each <code>x<\/code> of each <code>row<\/code> in <code>matrix<\/code><\/em>.<\/p>\n<h1>Execution order<\/h1>\n<p>That&#8217;s the question you asked, even if I&#8217;m not sure that&#8217;s the question you wanted to ask! In which order the operation are performed? The spec doesn&#8217;t seem to say anything on this question but the answer is: <em>it doesn&#8217;t matter, as long as you avoid side effects in your list comprehensions<\/em>. If you get a list out of a list comprehension (no exception raised), this list is guaranteed to complete, no matter how it was built.<\/p>\n<p>But if you don&#8217;t follow the &#8220;no side-effect&#8221; rule, the order in which side effects are performed may change the final result.<br \/>\nYou can use a trick to test it: the <code>print<\/code> function returns <code>None<\/code>, hence <code>if not print(...)<\/code> is always <code>True<\/code>:<\/p>\n<pre><code>&gt;&gt;&gt; matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n&gt;&gt;&gt; squared = [[x**2 for x in row if not print(\"value\", x)] for row in matrix if not print(\"row\", row)]\nrow [1, 2, 3]\nvalue 1\nvalue 2\nvalue 3\nrow [4, 5, 6]\nvalue 4\nvalue 5\nvalue 6\nrow [7, 8, 9]\nvalue 7\nvalue 8\nvalue 9\n&gt;&gt;&gt; squared\n[[1, 4, 9], [16, 25, 36], [49, 64, 81]]\n<\/code><\/pre>\n<p>The order seems &#8220;natural&#8221;, but I don&#8217;t think you should rely on it (<strong>more important: you should not have side effects in your list comprehensions<\/strong>).<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Python List comprehension execution order [duplicate] <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Order of elements The PEP 202 is not very&#8230; comprehensive, but you can found some information in the Python Language Reference: The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those &#8230; <a title=\"[Solved] Python List comprehension execution order [duplicate]\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\" aria-label=\"More on [Solved] Python List comprehension execution order [duplicate]\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[1941,349],"class_list":["post-10853","post","type-post","status-publish","format-standard","hentry","category-solved","tag-list-comprehension","tag-python"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Python List comprehension execution order [duplicate] - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Python List comprehension execution order [duplicate] - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Order of elements The PEP 202 is not very&#8230; comprehensive, but you can found some information in the Python Language Reference: The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-25T00:06:28+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Python List comprehension execution order [duplicate]\",\"datePublished\":\"2022-09-25T00:06:28+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\"},\"wordCount\":388,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"list-comprehension\",\"python\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\",\"name\":\"[Solved] Python List comprehension execution order [duplicate] - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-25T00:06:28+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Python List comprehension execution order [duplicate]\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Python List comprehension execution order [duplicate] - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Python List comprehension execution order [duplicate] - JassWeb","og_description":"[ad_1] Order of elements The PEP 202 is not very&#8230; comprehensive, but you can found some information in the Python Language Reference: The comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/","og_site_name":"JassWeb","article_published_time":"2022-09-25T00:06:28+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Python List comprehension execution order [duplicate]","datePublished":"2022-09-25T00:06:28+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/"},"wordCount":388,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["list-comprehension","python"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/","url":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/","name":"[Solved] Python List comprehension execution order [duplicate] - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-25T00:06:28+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-python-list-comprehension-execution-order-duplicate\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Python List comprehension execution order [duplicate]"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10853","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=10853"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10853\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=10853"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=10853"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=10853"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}