<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Naveed Fida on Medium]]></title>
        <description><![CDATA[Stories by Naveed Fida on Medium]]></description>
        <link>https://medium.com/@naveedfida01?source=rss-21cfd0fd6015------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z5VYfOPUdcv4gkDB30SP6g.png</url>
            <title>Stories by Naveed Fida on Medium</title>
            <link>https://medium.com/@naveedfida01?source=rss-21cfd0fd6015------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:38:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naveedfida01/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Comprehending Python Comprehensions]]></title>
            <link>https://medium.com/@naveedfida01/comprehending-python-comprehensions-223852afc4bb?source=rss-21cfd0fd6015------2</link>
            <guid isPermaLink="false">https://medium.com/p/223852afc4bb</guid>
            <category><![CDATA[dictionary-comprehension]]></category>
            <category><![CDATA[python-list-comprehension]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Naveed Fida]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 17:50:06 GMT</pubDate>
            <atom:updated>2023-04-08T17:50:06.578Z</atom:updated>
            <content:encoded><![CDATA[<p>Advancements in programming have always been about finding the best abstractions and idioms to express a certain piece of logic and solve a problem. Filtering and mapping a list of data items is as old a programming problem as programming has existed and the number of ways you can solve this problem across programming languages and paradigms is vast. Let’s see an example. Let’s say we have a list of dictionaries representing some applicants and we want to narrow the list down to people above the age of 21.</p><pre>people = [<br>  {&#39;name&#39;: &#39;Joe&#39;, &#39;age&#39;: 20},<br>  {&#39;name&#39;: &#39;Ben&#39;, &#39;age&#39;: 24},<br>  {&#39;name&#39;: &#39;Heather&#39;, &#39;age&#39;: 19},<br>  {&#39;name&#39;: &#39;Harry&#39;, &#39;age&#39;: 27}<br>]<br><br>people_above_21 = []<br><br>for person in people:<br>  if person[&quot;age&quot;] &gt; 21:<br>    people_above_21.append(person)</pre><p>A simple for or even while loop is more than enough to do the job. But these are lower-level primitives available in almost all languages. A more high-level and functional approach would be to use the built-in python function filter:</p><pre>people_above_21 = list(filter(lambda person: person[&#39;age&#39;] &gt; 21, people))<br><br># [{&#39;name&#39;: &#39;Ben&#39;, &#39;age&#39;: 24}, {&#39;name&#39;: &#39;Harry&#39;, &#39;age&#39;: 27}]</pre><p>The above implementation is certainly an improvement in terms of conciseness and expressiveness. However, one can argue that python’s implementation of these functional primitives is slightly unweildly. Enter list comprehensions. The above can rewritten as follows:</p><pre>people_above_21 = [person for person in people if person[&#39;age&#39;] &gt; 21 ]<br><br># [{&#39;name&#39;: &#39;Ben&#39;, &#39;age&#39;: 24}, {&#39;name&#39;: &#39;Harry&#39;, &#39;age&#39;: 27}]</pre><p>This to me seems very expressive and conveys the intent of the author much more clearly. It almost reads like “select each person in the list people whose age is greater than 21”. The purpose of programming languages has always been more to communicate with people rather than computers and this does the job nicely on that front.</p><p>This is called a comprehension. In particular, this is a list comprehension because we’re getting a list as a result of this operation. More generally, a list comprehension can be written as:</p><pre>[&lt;expression_using_variable&gt; for &lt;variable&gt; in &lt;iterable&gt; if &lt;condition&gt;]</pre><p>Note that the first part of the comprehension doesn’t have to be just the variable, it can be any expression that uses the variable. The same applies to the condition expression. For example, we’d use the following comprehension if we wanted to get only the ages of the people above 21:</p><pre>names_of_people_above_21 = [person[&#39;name&#39;] for person in people if person[&#39;age&#39;] &gt; 21]</pre><p>Also note the &lt;iterable&gt; instead of &lt;list&gt;. This means that we can use any python object that can be iterated over, including strings:</p><pre>[x for x in &quot;hello&quot;] # creates a list: [&#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]</pre><p>The above also shows that the condition part of the comprehension is optional. If you leave it out, the operation becomes similar to the built-in map function. Another example of such use would be if we wanted to get the names of all the people in the people list. In essence, we want a list that <em>maps</em> each person in the list to his/her name:</p><pre>names = [person[&#39;name&#39;] for person in people] # [&#39;Joe&#39;, &#39;Ben&#39;, &#39;Heather&#39;, &#39;Harry&#39;]</pre><h3>Dictionary Comprehensions</h3><p>So far, we’ve looked at comprehensions that yield new lists based on a given iterable. Comprehensions can also yield new dictionaries. Let’s say we have a list of numbers that we want to convert to a dictionary with the numbers as the keys and the square of the numbers as the values. Here’s how we’d do that:</p><pre>numbers = [1, 2, 3, 4]<br>square_dict = {n: n * n for n in numbers} # {1: 1, 2: 4, 3: 9, 4: 16}</pre><p>Notice the use of curly braces ({}) instead of brackets for dictionary comprehensions. We can also use a conditional here. Let’s get a dictionary of squares that only includes even numbers:</p><pre>square_dict = {n: n * n for n in numbers if n % 2 == 0} # {2: 4, 4: 16}</pre><p>Comprehensions are a great way to produce new lists and dictionaries by manipulating iterables. It’s a construct borrowed from functional languages and it has been increasingly gaining popularity in python. I often look for opportunities to convert my procedural code to comprehensions where possible. It makes my programs more readable and that should always be an important goal when writing python programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223852afc4bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>