{"id":405,"date":"2017-09-11T18:41:14","date_gmt":"2017-09-11T23:41:14","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=405"},"modified":"2019-06-15T16:50:56","modified_gmt":"2019-06-15T21:50:56","slug":"python-how-to-use-list-comprehensions","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2017\/09\/11\/python-how-to-use-list-comprehensions\/","title":{"rendered":"Python: How to use List Comprehensions"},"content":{"rendered":"<p>List Comprehensions were introduced to the Python language in <a href=\"https:\/\/www.python.org\/dev\/peps\/pep-0202\/\">PEP-202<\/a> to provide a more concise syntactical way to produce lists where <code>map()<\/code>, <code>filter()<\/code>, <code>for loops<\/code>, and <code>if statements<\/code> would normally be used.<\/p>\n<p>A list comprehension can be summed up like this:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">new_list = [item action for item in existing_list with optional if condition]<\/code><\/p>\n<p>This is a Pythonic way of representing in one line, what normally would take 3 lines in a for loop. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">for item in list:\n    if condition:\n        item action<\/pre>\n<p>Let&#8217;s say you have a list of words saved in existing_list like so:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">existing_list = ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dogs.']<\/code><\/p>\n<p>You could use a for loop to iterate through the list and save the length of each word to a new list. This takes three lines of code. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">word_list = []\nfor item in existing_list:\n    word_list.append(len(item))<\/pre>\n<p>Which yields:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[3, 5, 5, 3, 6, 4, 3, 4, 5]<\/code><\/p>\n<p>We can use list comprehension here (without a conditional), and we&#8217;re down to one line of code. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">word_list = [len(item) for item in existing_list]<\/pre>\n<p>Which yields:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[3, 5, 5, 3, 6, 4, 3, 4, 5]<\/code><\/p>\n<p>Now to extend this example, we can add a conditional. Let&#8217;s say we want a list of only the words with a length greater than 3 characters. Using a for loop, we would add a conditional if statement. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">over_three = []\nfor item in existing_list:\n    if len(item) &gt; 3:\n        over_three.append(item)\n\nprint over_three<\/pre>\n<p>Now with list comprehension:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">over_three = [item for item in existing_list if len(item) &gt; 3]\nprint over_three<\/pre>\n<p>Both methods yield:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">['quick', 'brown', 'jumped', 'over', 'lazy', 'dogs.']<\/code><\/p>\n<p>One more example, this time using the\u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">range()<\/code>function:<\/p>\n<p>Let&#8217;s say you want to perform a math operation on a range of numbers from 0 to 25. For this example, lets generate a list of the squares of each number. Using a for loop, we could do this like so:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">squares = []\nfor num in range(25):\n    squares.append( num **2 )\n\nprint squares<\/pre>\n<p>Using list comprehension:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">squares = [num **2 for num in range(25)]\n\nprint squares<\/pre>\n<p>Both methods yield:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576]<\/code><\/p>\n<p>Now let&#8217;s add a conditional so that we get only the results that end in &#8216;1&#8217;.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">squares1 = [num **2 for num in range(25) if str(num**2).endswith('1')]\n\nprint squares1<\/pre>\n<p>Which yields:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[1, 81, 121, 361, 441]<\/code><\/p>\n<p><strong>How to build a 5 by 6 matrix of random floats:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import random\n\nrandom_matrix = [[random.random() for x in range(5)] for x in range(6)]\nfor r in random_matrix:\n    print r<\/pre>\n<p>Which yields:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[0.8105065135499314, 0.8865204268844189, 0.41117784467229923, 0.9693965072402817, 0.04377154159472296]\n[0.4449164960699984, 0.44640332641180247, 0.20461691125671944, 0.17777546880568984, 0.36790015258108355]\n[0.3760034086651669, 0.39668698338668795, 0.05160356609769412, 0.32830220357773043, 0.3401325448631197]\n[0.6261611276967547, 0.2871336278152169, 0.7117654068095559, 0.4853165792408366, 0.8915682478339392]\n[0.03019253085736151, 0.3430835985441516, 0.10963927711317467, 0.9270460983912879, 0.4967079233264775]\n[0.4716454274374533, 0.9139922867709204, 0.37298027208003715, 0.7032776930420336, 0.9368315074777497]<\/pre>\n<p><strong>How to build a 5 by 6 matrix of random integers:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import random\n\nrandom_matrix = [[random.randint(0,9) for x in range(5)] for x in range(6)]\nfor r in random_matrix:\n    print r\n<\/pre>\n<p>Which yields:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">[9, 8, 0, 8, 6]\n[1, 1, 9, 6, 1]\n[5, 6, 1, 3, 3]\n[4, 2, 7, 2, 9]\n[5, 7, 6, 8, 2]\n[8, 8, 3, 6, 6]<\/pre>\n<p><strong>Some other examples:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\"># Print only numbers divisible by 2\nprint [i for i in range(20) if i%2 == 0]\n\n# Using two ranges\nprint [x+y for x in [10,30,50] for y in [25,45,65]]\n\n# Using a function call\ndef triple(x):\n    return x*3\n\nprint [triple(x) for x in range(10) if x%2==0]\n\n# Using isdigit()\nstring = \"Hello 12345 World\"\nnumbers = [x for x in string if x.isdigit()]\nprint numbers\n\n# Using lower() and upper()\nprint [x.lower() for x in [\"A\",\"B\",\"C\"]]\nprint [x.upper() for x in [\"a\",\"b\",\"c\"]]\n\n# First letter in each word\nexisting_list = ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dogs.']\nf = [word[0] for word in existing_list]\n\n# List Comprehension inside a for loop!\nfor\u00a0row\u00a0in\u00a0[[i*j\u00a0for\u00a0i\u00a0in\u00a0range(1,\u00a08)]\u00a0for\u00a0j\u00a0in\u00a0range(1,\u00a04)]:\n\u00a0\u00a0\u00a0\u00a0print\u00a0row\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>List Comprehensions were introduced to the Python language in PEP-202 to provide a more concise syntactical way to produce lists where map(), filter(), for loops, and if statements would normally be used. A list comprehension can be summed up like this: new_list = [item action for item in existing_list with optional if condition] This is &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2017\/09\/11\/python-how-to-use-list-comprehensions\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Python: How to use List Comprehensions<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[30,4],"class_list":["post-405","post","type-post","status-publish","format-standard","hentry","category-python-language","tag-list-comprehensions","tag-python"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/405","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=405"}],"version-history":[{"count":21,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/405\/revisions"}],"predecessor-version":[{"id":2788,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/405\/revisions\/2788"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=405"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=405"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=405"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}