<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-558019147766984999</atom:id><lastBuildDate>Mon, 07 Oct 2024 05:16:03 +0000</lastBuildDate><category>Programming</category><category>Python</category><category>Cheat Sheet</category><category>Data types</category><category>List Comprehension</category><category>Comprehensions</category><category>Flask</category><category>Iteration</category><category>List</category><title>Learn Python</title><description>Python lessons, tips and tricks for beginners!</description><link>https://mypythonlessons.blogspot.com/</link><managingEditor>noreply@blogger.com (Shyama Sankar)</managingEditor><generator>Blogger</generator><openSearch:totalResults>10</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-5432599432737586979</guid><pubDate>Mon, 01 Apr 2019 07:50:00 +0000</pubDate><atom:updated>2019-04-02T22:34:50.470-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Flask</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Getting started with Flask: Hello World</title><description>In this post, we will learn how to create a very basic &quot;Hello World&quot; web application using Flask and run it locally.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h2&gt;
Installation and setup&lt;/h2&gt;
&lt;div&gt;
In this section, we will install Flask and set up our project environment.&lt;/div&gt;
&lt;div&gt;
Note: The commands I am providing are for setting it up on a MacBook. If you use a different OS, refer to Flask&#39;s installation guide:&amp;nbsp;&lt;a href=&quot;http://flask.pocoo.org/docs/1.0/installation/#installation&quot; target=&quot;_blank&quot;&gt;http://flask.pocoo.org/docs/1.0/installation/#installation&lt;/a&gt;. But the steps basically remain the same.&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Install Python. I am using Python3.&lt;/li&gt;
&lt;li&gt;Create a directory for your project, say, &quot;hello&quot; and go inside the directory.&lt;/li&gt;
&lt;pre&gt;mkdir hello
cd hello
&lt;/pre&gt;
&lt;li&gt;Now create a virtual environment and activate it.&lt;/li&gt;
&lt;pre&gt;python3 -m venv venv
. venv/bin/activate&lt;/pre&gt;
&lt;li&gt;Then install Flask within the virtual environment.&lt;/li&gt;
&lt;pre&gt;pip3 install flask
&lt;/pre&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2&gt;
Create the Hello World application
&lt;/h2&gt;
&lt;div&gt;
Now let us create our Hello World application.&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Within the project directory, &#39;hello&#39;, create a file, &#39;hello.py&#39;. This is where we are going to write the code for our application.&lt;/li&gt;
&lt;li&gt;First, we need to import the module &lt;i&gt;flask&lt;/i&gt; and create an instance of class &lt;i&gt;Flask.&lt;/i&gt;&lt;br /&gt;
&lt;pre&gt;from flask import Flask
app = Flask(__name__)
&lt;/pre&gt;
The &lt;i&gt;Flask&lt;/i&gt; class implements a WSGI (Web Server Gateway Interface) application. We should pass the name of the Python module or package of our application to it. In this case, we are not creating a package. We are simply creating a module &#39;hello.py&#39;. Note that __name__ here refers to the name of the module.&lt;/li&gt;
&lt;li&gt;Next, we will define our hello world method.&lt;br /&gt;This method returns whatever we want to show in our app.&lt;/li&gt;
&lt;pre&gt;def hello_world():
  return &quot;Hello World!&quot;
&lt;/pre&gt;
&lt;li&gt;Finally, we should link this method with a URL. In Flask, we can use the &lt;i&gt;route()&lt;/i&gt;&amp;nbsp;decorator to define which URL should trigger a function.&lt;/li&gt;
&lt;pre&gt;@app.route(&#39;/&#39;)
def hello_world():
  return &quot;Hello World!&quot;
&lt;/pre&gt;
This would make the application display &quot;Hello World!&quot; to the console when we go to our website&#39;s base URL.&lt;/ul&gt;
&lt;/div&gt;
So, now we have a file hello.py with the following content:&lt;br /&gt;
&lt;pre&gt;from flask import Flask
app = Flask(__name__)

@app.route(&#39;/&#39;)
def hello_world():
  return &quot;Hello World!&quot;
&lt;/pre&gt;
&lt;br /&gt;
&lt;h2&gt;
Run the application locally&lt;/h2&gt;
&lt;div&gt;
In this section we will see how to run our application locally on our device.&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;First, tell the terminal which flask application to run. In our case, the application is defined by the &#39;hello.py&#39; module. Flask uses the environment variable &#39;FLASK_APP&#39; while looking for the application. So let us set its value.&lt;/li&gt;
&lt;pre&gt;export FLASK_APP=hello.py
&lt;/pre&gt;
&lt;li&gt;Now run the application. We have two options for running a flask application.&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;Using &lt;b&gt;flask run&lt;/b&gt;&lt;/li&gt;
&lt;pre&gt;flask run
&lt;/pre&gt;
&lt;li&gt;Using &lt;b&gt;python -m flask&lt;/b&gt;&lt;/li&gt;
&lt;pre&gt;python -m flask run
&lt;/pre&gt;
&lt;/ol&gt;
This should display something like this on the console:
&lt;pre&gt;Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
&lt;/pre&gt;
&lt;li&gt;Let it run and go to a browser and enter the URL &quot;http://127.0.0.1:5000/&quot; in it. You should see our application in action.&lt;/li&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/ul&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQOorN0ejuKjj8ZyHXKokl1jtHg-vq-TCuy5eSAKaKqxHbaT-ir8zrGHqH4qKb4WZNdCmuGnsjXddmjfNnym1M2GglKRVaLWJ2QoLYnxjkDphDKa0JEZ-QvudzZCDDq-FCT9QiKXp4OPY/s1600/hello_world.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;154&quot; data-original-width=&quot;518&quot; height=&quot;59&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQOorN0ejuKjj8ZyHXKokl1jtHg-vq-TCuy5eSAKaKqxHbaT-ir8zrGHqH4qKb4WZNdCmuGnsjXddmjfNnym1M2GglKRVaLWJ2QoLYnxjkDphDKa0JEZ-QvudzZCDDq-FCT9QiKXp4OPY/s200/hello_world.png&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;h2&gt;
Useful tips&lt;/h2&gt;
&lt;h3&gt;
Development environment&lt;/h3&gt;
&lt;div&gt;
Earlier, when we ran our flask application, you would have seen an output like:&lt;/div&gt;
&lt;pre&gt;flask run                      
 * Serving Flask app &quot;hello.py&quot;
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
&lt;/pre&gt;
&lt;div&gt;
This basically means that we were using &quot;production&quot; environment with &quot;debug&quot; mode turned on for our development purposes. One issue with this during development is that, whenever we make a code change, we would have to restart the application.&lt;/div&gt;
&lt;div&gt;
Flask provides a &quot;development&quot; environment for dev purposes and this can be very helpful. In &quot;development&quot; environment, the application is reloaded automatically whenever we make a code change. Also, the debug mode gets enabled and the debugger gets activated. You can change the environment by using the &quot;FLASK_ENV&quot; variable:&lt;/div&gt;
&lt;pre&gt;export FLASK_ENV=development
flask run
 * Serving Flask app &quot;hello.py&quot; (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 299-503-654
&lt;/pre&gt;
&lt;div&gt;
You may also choose to just enable the debug mode by using environment variable &quot;FLASK_DEBUG&quot;:&lt;/div&gt;
&lt;pre&gt;flask run                  
 * Serving Flask app &quot;hello.py&quot; (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 299-503-654
&lt;/pre&gt;
&lt;h4&gt;
Logging&lt;/h4&gt;
&lt;div&gt;
Logging is another important feature that is useful while getting started. Flask provides a preconfigured logger(since version 0.3). This is a standard Python logger. Sample usage:&lt;/div&gt;
&lt;pre&gt;app.logger.info(&#39;Info message...&#39;)
app.logger.debug(&#39;Debug message...&#39;)
app.logger.warning(&#39;Warning message...&#39;)
app.logger.error(&#39;Error message...&#39;)
&lt;/pre&gt;
&lt;h2&gt;
Conclusion&lt;/h2&gt;
&lt;div&gt;
We discussed how to create a very basic &quot;Hello World&quot; app using Flask and run it in our local environments.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/04/getting-started-with-flask-hello-world.html</link><author>noreply@blogger.com (Shyama Sankar)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjQOorN0ejuKjj8ZyHXKokl1jtHg-vq-TCuy5eSAKaKqxHbaT-ir8zrGHqH4qKb4WZNdCmuGnsjXddmjfNnym1M2GglKRVaLWJ2QoLYnxjkDphDKa0JEZ-QvudzZCDDq-FCT9QiKXp4OPY/s72-c/hello_world.png" height="72" width="72"/><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-8012199407911830871</guid><pubDate>Sat, 30 Mar 2019 11:43:00 +0000</pubDate><atom:updated>2019-03-30T04:47:53.751-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Monkey Patching in Python: Explained with Examples</title><description>In this post, we will learn about monkey patching, i.e., how to dynamically update code behavior at runtime. We will also see some useful examples of monkey patching in Python.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h2&gt;
Table of contents&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#Intro&quot;&gt;Monkey patching&lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#What&quot;&gt;What is monkey patching?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#WhyUse&quot;&gt;Why use monkey patching?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#WhenToUse&quot;&gt;When is monkey patching used?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#Caution&quot;&gt;Cautionary note: Why monkey patching should be used carefully&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;&lt;a href=&quot;#MonkeyPatchingInPython&quot;&gt;Monkey patching in Python&lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#E1&quot;&gt;Example 1: Monkey patching the value of a module&#39;s attribute&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E2&quot;&gt;Example 2: Monkey patching to extend the&amp;nbsp;behavior of a method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E3&quot;&gt;Example 3: Monkey patching to change the&amp;nbsp;behavior of a method&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E4&quot;&gt;Example 4: Monkey patching class attributes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E5&quot;&gt;Example 5: Monkey patching a specific instance&#39;s attributes&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E6&quot;&gt;Example 6: Monkey patching a class&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E7&quot;&gt;Example 7: Monkey patching a module&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;&lt;a href=&quot;#Conclusion&quot;&gt;Conclusion&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id=&quot;Intro&quot;&gt;
Monkey patching&lt;/h2&gt;
&lt;h3 id=&quot;What&quot;&gt;
&lt;b&gt;What is monkey patching?&lt;/b&gt;&lt;/h3&gt;
Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.&lt;br /&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;WhyUse&quot;&gt;
&lt;b&gt;Why use monkey patching?&lt;/b&gt;&lt;/h3&gt;
It allows us to modify or extend the behavior of libraries, modules, classes or methods at&amp;nbsp;runtime without actually modifying the source code.&lt;br /&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;h3 id=&quot;WhenToUse&quot;&gt;
&lt;b&gt;When is monkey patching used?&lt;/b&gt;&lt;/h3&gt;
&lt;div&gt;
Some common applications of monkey patching are:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;To extend or modify the behavior of third-party or built-in libraries or methods at runtime without touching the original&amp;nbsp;code.&lt;/li&gt;
&lt;li&gt;During testing to mock the behavior of libraries, modules, classes or any objects.&lt;/li&gt;
&lt;li&gt;To quickly fix some issues if we do not have the time or resources to roll-out a proper fix to the original software.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3 id=&quot;Caution&quot;&gt;
&lt;b&gt;Cautionary note: Why monkey patching should be used carefully&lt;/b&gt;&lt;/h3&gt;
&lt;div&gt;
Monkey patching should be used very carefully, especially if used in production software (would not recommend unless absolutely necessary). Some of the reasons are:&lt;br /&gt;
&lt;ul&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;If we change the behavior of a method by monkey patching, it no longer behaves the way it was documented. So unless every client or user is aware of this change, it could cause their code to behave unexpectedly.&lt;/li&gt;
&lt;li&gt;It makes it harder to troubleshoot issues.&lt;/li&gt;
&lt;li&gt;If we are monkey patching a method in one module and another module is using that same method after the patch is applied, then the second module will also end up seeing the monkey patched method instead of its original version. This can lead to unwanted bugs.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id=&quot;MonkeyPatchingInPython&quot;&gt;
Monkey patching in Python&lt;/h2&gt;
&lt;div&gt;
In Python, modules or classes are just like any other mutable objects like lists, i.e., we can modify them or their attributes including functions or methods at runtime. Let us go through some examples to understand this clearly and learn how to monkey patch in Python.&lt;/div&gt;
&lt;h3 id=&quot;E1&quot;&gt;
Example 1: Monkey patching the value of a module&#39;s attribute&lt;/h3&gt;
&lt;div&gt;
As a basic example, let us see how we could update a module&#39;s attribute. We will be updating the value of &quot;pi&quot; in the &quot;math&quot; module so that its precision is reduced to 3.14.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/9e43bfa2a5ed6c5ffeace8ca1bd1b8dc.js&quot;&gt;&lt;/script&gt;&lt;/div&gt;
&lt;div&gt;
Note how we took a backup of the original value before our computation and then removed the patch at the end. This is a good practice, especially in tests, to avoid messing up the whole test suite.&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E2&quot;&gt;
Example 2: Monkey patching to extend the&amp;nbsp;behavior of a method&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
In this example, we will see how to extend the behavior of a method using monkey patching. We will take a look at how to update the builtin print method in Python3 to include a timestamp.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/fb8452b6d08e5546b224d8fdc19e4e6e.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E3&quot;&gt;
Example 3: Monkey patching to change the&amp;nbsp;behavior of a method&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
Now let us see how to completely change the behavior of a method. This can be particularly useful in unit tests to mock complex methods, with external dependencies (network, database, etc). Here, we will take a look at how to replace a method with another.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/560a658ac30befb3ba2fe07cb610e89d.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E4&quot;&gt;
Example 4: Monkey patching class attributes&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
So far, we have been updating attributes or methods at the module level. Now let us take a look at how to monkey patch a class attribute. Note that this modifies the attribute for the class itself, all of its instances will see the patched attribute.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/a162d544879a7e339a1e30101134f61f.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E5&quot;&gt;
Example 5: Monkey patching a specific instance&#39;s attributes&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
The previous example showed how to monkey patch a class attribute. Here we will see how to patch just a specific instance&#39;s attribute.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/b3cd3d2c040868cf029fda8331b753a7.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div&gt;
Note that we made use of the MethodType method from types module in Python to bind the patched method to just one instance. This assures that other instances of the class are not affected.&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E6&quot;&gt;
Example 6: Monkey patching a class&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
Now let us see how we would monkey patch a class. Since a class is also just an object, we can monkey patch it with any other object. Here we will see an example of patching it with another class.&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/751ee7a5500e59634ebd71f36bfce6c0.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;h3 id=&quot;E7&quot;&gt;
Example 7: Monkey patching a module&lt;/h3&gt;
&lt;/div&gt;
&lt;div&gt;
As the last example, let us see how we can patch an entire module. This works the same way as any other Python object.&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/78996b342f01be1e60858add2c4c2718.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;h2 id=&quot;Conclusion&quot;&gt;
Conclusion&lt;/h2&gt;
&lt;div&gt;
Monkey patching is a cool technique and now we have learned how to do that in Python. However, as we discussed, it has its own&amp;nbsp;drawbacks and should be used carefully.&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/monkey-patching-in-python-explained.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-7874878802403372794</guid><pubDate>Fri, 29 Mar 2019 07:44:00 +0000</pubDate><atom:updated>2019-03-29T00:49:25.486-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Iteration</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Iteration in Python: The for, while, break, and continue statements</title><description>In this post, we will discuss iterations in Python. We will go over what iteration is, the two types of iterations (definite and indefinite), and the Python statements used for implementing iterations- &lt;i&gt;for &lt;/i&gt;and &lt;i&gt;while&lt;/i&gt;. We will also discuss the &lt;i&gt;break &lt;/i&gt;and &lt;i&gt;continue &lt;/i&gt;statements and see how they are used to alter the flow of an iteration.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;h2&gt;
What is an iteration?&lt;/h2&gt;
&lt;div&gt;
&lt;i&gt;Iteration&amp;nbsp;&lt;/i&gt;is defined as the repetition of a process.&lt;br /&gt;
&lt;br /&gt;
Let&#39;s say, we have a set of files on our computer and we wanted to append their names with a serial number. What would we do? We would rename every file one by one. So basically, we are &lt;i&gt;iterating&lt;/i&gt; over every file and renaming them.&lt;br /&gt;
&lt;br /&gt;
In programming, &lt;i&gt;iteration&lt;/i&gt;&amp;nbsp;or &lt;i&gt;looping&amp;nbsp;&lt;/i&gt;is the act of repeatedly executing a block of code.&lt;br /&gt;
&lt;h2&gt;
Types of iteration&lt;/h2&gt;
Depending on the way in which the number of iterations is determined, there are two types of iterations or loops:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Definite iteration or loop&lt;/b&gt;&lt;br /&gt;If the number of iterations is predetermined when we start the loop, then it is called &lt;i&gt;definite&lt;/i&gt;. For example, &lt;i&gt;repeat renaming a file for 10 files in a directory&lt;/i&gt;.&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Indefinite iteration or loop&lt;/b&gt;&lt;br /&gt;If the number of iterations is not known when we start the loop, then it is called &lt;i&gt;indefinite&lt;/i&gt;. For example, &lt;i&gt;repeat moving the first file in a directory to another while it is not empty.&lt;/i&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
Now let us see how we can implement &lt;i&gt;iteration&lt;/i&gt; in Python.&lt;/div&gt;
&lt;/div&gt;
&lt;h2&gt;
The&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;statement: Indefinite iteration in Python&lt;/h2&gt;
&lt;div&gt;
The &lt;i&gt;while &lt;/i&gt;statement is used to execute a set of statements as long as an expression evaluates to &lt;i&gt;true&lt;/i&gt;. In Python, the &lt;i&gt;while &lt;/i&gt;statement comes with an optional &lt;i&gt;else &lt;/i&gt;condition which allows us to execute another set of statements if the expression evaluates to &lt;i&gt;false&lt;/i&gt;. Let&#39;s take a look at the syntax.&lt;/div&gt;
&lt;h3&gt;
Syntax&lt;/h3&gt;
&lt;div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/79ef885fc736872a2e5952ffb170c919.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;div&gt;
The &lt;i&gt;expression&lt;/i&gt; is repeatedly evaluated and &lt;i&gt;set_of_statements_1&amp;nbsp;&lt;/i&gt;is executed as long as the &lt;i&gt;expression&lt;/i&gt;&amp;nbsp;evaluates to true. Once the &lt;i&gt;expression&lt;/i&gt;&amp;nbsp;evaluates to false, then&amp;nbsp;&lt;i&gt;set_of_statements_2&lt;/i&gt;&amp;nbsp;is executed&lt;i&gt;.&lt;/i&gt;&amp;nbsp;Note that the else clause is optional. If the&amp;nbsp;&lt;i&gt;else&lt;/i&gt;&amp;nbsp;block is not there, we just break out of the loop once the &lt;i&gt;expression &lt;/i&gt;becomes false.&lt;br /&gt;
&lt;br /&gt;
As you can see, we do not specify the exact number of times the loop would execute. Hence, the&amp;nbsp;&lt;i&gt;while &lt;/i&gt;statement is suited for implementing &lt;i&gt;indefinite&lt;/i&gt;&amp;nbsp;loops.&lt;/div&gt;
&lt;h3&gt;
Examples&lt;/h3&gt;
&lt;/div&gt;
&lt;h4&gt;
1. Basic &lt;i&gt;while&lt;/i&gt; loop&lt;/h4&gt;
&lt;div&gt;
The following example shows a basic &lt;i&gt;while&lt;/i&gt; loop used to &lt;i&gt;pop&lt;/i&gt;&amp;nbsp;elements from a &lt;i&gt;list&lt;/i&gt;&amp;nbsp;and print them.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/262cfec149d4f374ef1dd82c02b5bb8b.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
2. &lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop with &lt;i&gt;else&lt;/i&gt;&lt;/h4&gt;
&lt;div&gt;
Now let us see how we can modify the previous example to print some message when the list becomes empty. Note that if the expression never evaluates to true, then only the code block associated with &lt;i&gt;else&lt;/i&gt;&amp;nbsp;will get executed.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/39fc4cdb129acd41e7c84895c4de4635.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
3. Infinite &lt;i&gt;while &lt;/i&gt;loop&lt;/h4&gt;
&lt;div&gt;
We would end up with an infinite loop (a loop that would never end) if the expression always evaluates to true. Let us see an example.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/75443d37588fc8b17d52db9a986cb6a5.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
4. Nested &lt;i&gt;while &lt;/i&gt;loop&lt;/h4&gt;
&lt;div&gt;
Loops can be nested. Let us see an example for &lt;i&gt;nested-while&lt;/i&gt; loops.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/1c6d741b19d462a04e9d9f6e631c8d8c.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h2&gt;
The&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&lt;span style=&quot;font-weight: normal;&quot;&gt;&amp;nbsp;&lt;/span&gt;statement: Definite iteration in Python&lt;/h2&gt;
&lt;div&gt;
In Python, the &lt;i&gt;for&lt;/i&gt; statement is used to &lt;i&gt;iterate&lt;/i&gt; over the elements of an &lt;i&gt;iterable object&lt;/i&gt;&lt;i&gt;. &lt;/i&gt;A set of statements is executed for every item in the iterable. Similar to the &lt;i&gt;while&lt;/i&gt;&amp;nbsp;statement, the &lt;i&gt;for&lt;/i&gt;&amp;nbsp;statement also has an optional &lt;i&gt;else&lt;/i&gt;&amp;nbsp;clause. Let&#39;s see the syntax.&lt;/div&gt;
&lt;h3&gt;
Syntax&lt;/h3&gt;
&lt;div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/cd28c085b36a57d9edbdcebabff2eb75.js&quot;&gt;&lt;/script&gt; The &lt;i&gt;expression&amp;nbsp;&lt;/i&gt;is evaluated once. It is expected to yield an &lt;i&gt;iterable,&amp;nbsp;&lt;/i&gt;i.e., an object that can give us an &lt;i&gt;iterator&lt;/i&gt;&amp;nbsp;when called using the built-in &lt;i&gt;iter() &lt;/i&gt;function&lt;i&gt;. &lt;/i&gt;The&amp;nbsp;&lt;i&gt;set_of_statements_1 &lt;/i&gt;is executed once for every &lt;i&gt;element&lt;/i&gt;&amp;nbsp;obtained from the &lt;i&gt;iterator.&lt;/i&gt;&amp;nbsp;Once the &lt;i&gt;iterator&lt;/i&gt;&amp;nbsp;raises the &lt;i&gt;StopIteration&lt;/i&gt;&amp;nbsp;exception or once it becomes empty, the loop terminates. If the &lt;i&gt;else&lt;/i&gt;&amp;nbsp;clause is provided, then&amp;nbsp;&lt;i&gt;set_of_statements_2&lt;/i&gt;&amp;nbsp;is executed before terminating the loop.&lt;br /&gt;
&lt;br /&gt;
As you can see, the &lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop would do a &lt;i&gt;definite &lt;/i&gt;number of iterations, depending on how many elements are present in the iterator. So &lt;i&gt;for&lt;/i&gt;&amp;nbsp;loops are suited for implementing &lt;i&gt;definite&lt;/i&gt;&amp;nbsp;loops in Python.&lt;/div&gt;
&lt;h3&gt;
Examples&lt;/h3&gt;
&lt;h4&gt;
1. Basic&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop&lt;/h4&gt;
&lt;h4&gt;
&lt;div style=&quot;font-weight: 400;&quot;&gt;
The following code snippet shows a basic&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop that iterates over a list.&lt;/div&gt;
&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/807c523beaf6b2b64f1bb2bd11b54cd7.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
2.&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop with&amp;nbsp;&lt;i&gt;else&lt;/i&gt;&lt;/h4&gt;
&lt;h4&gt;
&lt;div style=&quot;font-weight: 400;&quot;&gt;
The following example shows a basic &lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop with an &lt;i&gt;else&lt;/i&gt;&amp;nbsp;clause.&lt;/div&gt;
&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/29c29fd1c2a022e8d793d23c1761285a.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
3. Nested&amp;nbsp;&lt;i&gt;for&amp;nbsp;&lt;/i&gt;loop&lt;/h4&gt;
&lt;h4&gt;
&lt;div style=&quot;font-weight: 400;&quot;&gt;
Now let us see an example for&amp;nbsp;&lt;i&gt;nested-for&lt;/i&gt;&amp;nbsp;loops.&lt;/div&gt;
&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/31dac5da7586c8b9dc9cb6ae51ac6791.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h2&gt;
The &lt;i&gt;break &lt;/i&gt;statement: Break out of a loop&lt;/h2&gt;
&lt;div&gt;
The &lt;i&gt;break&lt;/i&gt;&amp;nbsp;statement can be used to terminate the execution of a loop. It can only appear within a &lt;i&gt;for &lt;/i&gt;or &lt;i&gt;while &lt;/i&gt;loop. It allows us to break out of the nearest enclosing loop. If the loop has an &lt;i&gt;else&lt;/i&gt;&amp;nbsp;clause, then&amp;nbsp;the code block associated with it will not be executed if we use the&lt;i&gt; break&lt;/i&gt;&amp;nbsp;statement. Let us see some examples.&lt;/div&gt;
&lt;div&gt;
&lt;h4&gt;
1. &lt;i&gt;break &lt;/i&gt;within a&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Let us see how to &lt;i&gt;break&lt;/i&gt; out of a &lt;i&gt;while&lt;/i&gt; loop if and when a certain condition is met. We will also see how a&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop with an&amp;nbsp;&lt;i&gt;else&lt;/i&gt;&amp;nbsp;behaves when a&amp;nbsp;&lt;i&gt;break&lt;/i&gt;&amp;nbsp;statement is added to it. Note that the statements within the &lt;i&gt;else&lt;/i&gt; condition are not executed if we &lt;i&gt;break&lt;/i&gt; out of the &lt;i&gt;while&lt;/i&gt; loop.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/7d0bc640696d0b288c0e1b0abe5497ad.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;div&gt;
&lt;h4&gt;
2. &lt;i&gt;break&amp;nbsp;&lt;/i&gt;within an infinite&amp;nbsp;&lt;i&gt;while&amp;nbsp;&lt;/i&gt;loop&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Now let us see how we can modify an infinite &lt;i&gt;while&lt;/i&gt; loop to &lt;i&gt;break&lt;/i&gt; on a certain condition.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/93230ed86e4570852e8bcb33b5ea3c98.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;div&gt;
&lt;h4&gt;
3.&amp;nbsp;&lt;i&gt;break&amp;nbsp;&lt;/i&gt;within a&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Now we will see how to use &lt;i&gt;break&lt;/i&gt; within a basic &lt;i&gt;for&lt;/i&gt; loop. Similar to &lt;i&gt;while&lt;/i&gt;&amp;nbsp;loops, we will see that the statements within &lt;i&gt;else&lt;/i&gt;&amp;nbsp;condition do not get executed if we &lt;i&gt;break&lt;/i&gt;&amp;nbsp;out of the &lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/cdca304465d282277388e1ddb4031d29.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;div&gt;
&lt;h4&gt;
4.&amp;nbsp;&lt;i&gt;break&amp;nbsp;&lt;/i&gt;within nested loops&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Now we will see an example of nested &lt;i&gt;for&lt;/i&gt; and &lt;i&gt;while&lt;/i&gt; loops. Let us see how &lt;i class=&quot;&quot;&gt;break&lt;/i&gt; behaves with nested loops. Note that &lt;i&gt;break&lt;/i&gt; statement only breaks out of the nearest enclosing &lt;i&gt;for&lt;/i&gt; or &lt;i&gt;while&lt;/i&gt; loop.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/3bd252f8ab2368ca4b08142df1b0bb6b.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h2&gt;
The &lt;i&gt;continue &lt;/i&gt;statement: Continue with the next iteration&lt;/h2&gt;
&lt;div&gt;
The &lt;i&gt;continue &lt;/i&gt;statement allows us to skip the rest of the statements within one cycle of the loop and forces it to continue to the next cycle. Let&#39;s take a look at some examples.&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;h4&gt;
1.&amp;nbsp;&lt;i&gt;continue&amp;nbsp;&lt;/i&gt;within a&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Let us see how the &lt;i&gt;continue &lt;/i&gt;statement works in a&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop. Note that when &lt;i&gt;continue &lt;/i&gt;is encountered in a &lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop, it forces the loop to jump to the &lt;i&gt;expression.&lt;/i&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;&lt;/i&gt;&lt;/div&gt;
&lt;div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/01716515eb3b88cd8a6d74e81e985406.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
2.&amp;nbsp;&lt;i&gt;continue&lt;/i&gt;&lt;i&gt;&amp;nbsp;&lt;/i&gt;within a&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
Now let us see how it works in a &lt;i&gt;for &lt;/i&gt;loop. Note that if &lt;i&gt;continue&lt;/i&gt;&amp;nbsp;is encountered when we are at the last element of the &lt;i&gt;iterable&lt;/i&gt;, then the loop is terminated or we move on to the &lt;i&gt;else &lt;/i&gt;block if it is present.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/a79d8f3453db42f291825d3423819f45.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
3.&amp;nbsp;&lt;i&gt;continue&lt;/i&gt;&lt;i&gt;&amp;nbsp;&lt;/i&gt;within nested loops&lt;/h4&gt;
&lt;/div&gt;
&lt;div&gt;
The following code samples show how &lt;i class=&quot;&quot;&gt;continue&lt;/i&gt; works within nested loops. Note that the &lt;i&gt;continue&lt;/i&gt;&amp;nbsp;statement causes the nearest enclosing&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;or&amp;nbsp;&lt;i&gt;while&lt;/i&gt;&amp;nbsp;loop to continue with its next cycle.&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/0853fd2d7c6e20b30224813e82500f07.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h2&gt;
Useful Resources and Reference&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/reference/compound_stmts.html#the-while-statement&quot; target=&quot;_blank&quot;&gt;https://docs.python.org/3/reference/compound_stmts.html#the-while-statement&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/reference/compound_stmts.html#the-for-statement&quot; target=&quot;_blank&quot;&gt;https://docs.python.org/3/reference/compound_stmts.html#the-for-statement&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/reference/simple_stmts.html#the-break-statement&quot; target=&quot;_blank&quot;&gt;https://docs.python.org/3/reference/simple_stmts.html#the-break-statement&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement&quot; target=&quot;_blank&quot;&gt;https://docs.python.org/3/reference/simple_stmts.html#the-continue-statement&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/iteration-in-python-for-while-break-and.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-7061217882604747808</guid><pubDate>Sun, 24 Mar 2019 06:22:00 +0000</pubDate><atom:updated>2019-03-23T23:43:36.379-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Comprehensions</category><category domain="http://www.blogger.com/atom/ns#">List Comprehension</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>List, Set and Dictionary Comprehensions in Python</title><description>In this post, we will discuss the three Python comprehensions, i.e., list, set and dictionary comprehensions, with examples.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;h2&gt;
Table of Contents&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#I&quot;&gt;Introduction&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#A&quot;&gt;Advantages&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#LC&quot;&gt;List comprehension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#SC&quot;&gt;Set comprehension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#DC&quot;&gt;Dictionary comprehension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#RP&quot;&gt;Related posts&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;I&quot;&gt;
Introduction&lt;/h2&gt;
&lt;/div&gt;
Python comprehensions are essentially syntactic sugar used to create sequences from other sequences. They are commonly used to:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;create new sequences which are obtained by applying some operation on elements of a sequence.&lt;/li&gt;
&lt;li&gt;create a subsequence containing elements of a sequence which satisfy certain conditions.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
List comprehensions were introduced in Python 2.0. Later in Python 3, set and dictionary comprehensions were added. Here, we will discuss these comprehensions with examples.&lt;/div&gt;
&lt;h2 id=&quot;A&quot;&gt;
Advantages:&lt;/h2&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;&lt;b&gt;Concise&lt;/b&gt;&lt;br /&gt;They need fewer lines of code than a for-loop with or without conditions.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;More readable&lt;/b&gt;&lt;br /&gt;If you understand comprehensions, it is more readable. Also, this depends. Sometimes, it is better to go for a traditional for-loop if the conditions are too complicated.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;Faster&lt;/b&gt;&lt;br /&gt;Memory is pre-allocated, instead of performing an append every time.&lt;/li&gt;
&lt;li&gt;&lt;b&gt;More Pythonic&lt;/b&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;h2 id=&quot;LC&quot;&gt;
List Comprehensions&lt;/h2&gt;
&lt;div&gt;
List comprehension provides a concise way to create a new list from an iterable.&lt;br /&gt;
List comprehensions are created using enclosing square brackets []. Syntactically, it has an expression on elements from the original sequence, followed by zero or more for and if statements.&lt;br /&gt;
The following code snippet shows examples for list comprehensions.&lt;/div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/2e6a49d64adfa170d0373dfc43527c00.js&quot;&gt;&lt;/script&gt;

If you are having difficulty with understanding any of the examples, then&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Explained with Examples&lt;/a&gt; will be a good reference. There, I explain list comprehensions with 10 examples of increasing complexity. I have used similar or the same examples as those present here. Each example shows how to implement something using a for-loop and then how to re-write it using list comprehensions. The list comprehension syntax for each conversion and a screen recording for how it is done is also included in there.&lt;br /&gt;
&lt;h2 id=&quot;SC&quot;&gt;
Set Comprehensions&lt;/h2&gt;
&lt;div&gt;
Similar to list comprehensions, set comprehensions are used to create sets from an iterable. Syntactically, the only difference is that curly braces are used instead of square brackets.&lt;br /&gt; All examples from list comprehension are applicable here, the only difference is that you need to replace the enclosing &#39;[]&#39; with &#39;{}&#39; to get a set comprehension.&lt;br/&gt;
The following code snippet shows examples for set comprehensions and how it differs from list comprehension. &lt;/div&gt;
&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/9a6d6db9c8ff303a1dc5c5aaff59baac.js&quot;&gt;&lt;/script&gt;

&lt;h2 id=&quot;DC&quot;&gt;
Dictionary Comprehensions&lt;/h2&gt;
&lt;div&gt;
Dictionary comprehensions are used to create dictionaries from arbitrary key and value expressions. Similar to set comprehensions, curly braces are used in this case as well. The only difference from set comprehensions is that, instead of providing a single expression, we provide two expressions, one for the key and one for the value separated by a colon(:). All examples from list comprehension can be extended to dictionary comprehensions as well.&lt;br /&gt;
The following code snippet shows examples for dictionary comprehensions and how it differs from list and set comprehensions.
&lt;/div&gt;&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/5add4b34618ae7205458f8eff1cb8788.js&quot;&gt;&lt;/script&gt;
&lt;h2 id=&quot;RP&quot;&gt;
Related Posts&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions: Explained with 10 Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Lists: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Sets: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-dictionaries-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Dictionaries: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Tuples: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-4214616971831962172</guid><pubDate>Sat, 23 Mar 2019 19:20:00 +0000</pubDate><atom:updated>2019-03-30T11:52:16.544-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cheat Sheet</category><category domain="http://www.blogger.com/atom/ns#">Data types</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python Dictionaries: Cheat Sheet</title><description>A cheat sheet for &lt;i&gt;dictionaries&lt;/i&gt; in Python.&lt;br /&gt;
What is the dictionary datatype in Python? How to use it? Some key points and several examples of its usage.&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;
&lt;a href=&quot;#CS&quot;&gt;Jump to the cheat sheet&lt;/a&gt;&lt;br /&gt;
&lt;h3&gt;
Key points&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Dictionary is a commonly used collection datatype in Python; the others being&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;lists&lt;/a&gt;,&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;sets&lt;/a&gt;, and&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;tuples&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;A dictionary is essentially &lt;b style=&quot;font-style: italic;&quot;&gt;a set of key-value pairs, &lt;/b&gt;where, the &lt;b&gt;&lt;i&gt;keys should be unique and immutable&lt;/i&gt;&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;A dictionary is &lt;i&gt;&lt;b&gt;mutable&lt;/b&gt;&lt;/i&gt;, i.e., it can be modified in place after it is created. We can add, remove or update items in a dictionary.&lt;/li&gt;
&lt;li&gt;Keys could be of any immutable data type, i.e., string, number, or even a tuple of immutable objects. [Note: Immutable objects are objects which cannot be modified in place once they are created. Python&#39;s built-in immutable objects include numbers, strings, and tuples].&lt;/li&gt;
&lt;li&gt;Dictionaries are indexed using their keys.&lt;/li&gt;
&lt;li&gt;Dictionaries are created using a pair of curly braces, i.e., {}, or by using the dict() constructor.&lt;/li&gt;
&lt;li&gt;We can create and initialize a dictionary with items by adding a comma-separated list of key-value pairs within the curly braces. The &#39;dict&#39; constructor also takes an optional iterable, mapping, or keyword arguments as input.&lt;/li&gt;
&lt;li&gt;For examples on how to create a dictionary, add elements, update elements, remove elements, etc, see the cheat sheet.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3 id=&quot;CS&quot;&gt;
Cheat sheet&lt;/h3&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/7f6328e885feb7d49ebc09fe1146430f.js&quot;&gt;&lt;/script&gt;
&lt;h3 id=&quot;RP&quot;&gt;
Related Posts&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Lists: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Sets: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Tuples: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html&quot; target=&quot;_blank&quot;&gt;List, Set and Dictionary Comprehensions in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions: Explained with 10 Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3&gt;
Useful resources and references&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/tutorial/datastructures.html#dictionaries&quot; target=&quot;_blank&quot;&gt;Python documentation for dictionaries&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/library/stdtypes.html#dict&quot; target=&quot;_blank&quot;&gt;Python documentation for &#39;dict&#39; constructor&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/python-dictionaries-cheat-sheet.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-5077328057544729757</guid><pubDate>Wed, 20 Mar 2019 07:19:00 +0000</pubDate><atom:updated>2019-03-30T11:52:04.917-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cheat Sheet</category><category domain="http://www.blogger.com/atom/ns#">Data types</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python Sets: Cheat Sheet</title><description>A cheat sheet for &lt;i&gt;sets&lt;/i&gt; in Python. What is the &#39;set&#39; datatype in Python? How is it used?&lt;br /&gt;
&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/br&gt;
&lt;a href=&quot;#CS&quot;&gt;Jump to the cheat sheet&lt;/a&gt;&lt;br /&gt;
&lt;h3&gt;
Key points&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Unlike &lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;lists&lt;/a&gt;&amp;nbsp;and&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;tuples&lt;/a&gt;,&amp;nbsp;a set is an &lt;b&gt;&lt;i&gt;unordered&lt;/i&gt;&lt;/b&gt; &lt;b&gt;&lt;i&gt;collection of &lt;/i&gt;&lt;/b&gt;&lt;i&gt;&lt;b&gt;unique elements&lt;/b&gt;&lt;/i&gt;.&lt;/li&gt;
&lt;li&gt;A set can be created using the set() constructor. It takes an optional iterable as input.&lt;/li&gt;
&lt;li&gt;Sets with some elements can also be initialized using the curly braces (e.g., {1, 2, 3}).&lt;/li&gt;
&lt;li&gt;However, curly braces cannot be used to create an empty set. Using empty curly braces, i.e., {}, creates a dictionary datatype in Python.&lt;/li&gt;
&lt;li&gt;&#39;in&#39; operator can be used to check the presence of an element in a set.&lt;/li&gt;
&lt;li&gt;Sets support the mathematical set operations like union, intersection, difference, symmetric difference, etc.&lt;/li&gt;
&lt;li&gt;Sets are mutable, we can add or remove elements from them.&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3 id=&quot;CS&quot;&gt;
Cheat sheet&lt;/h3&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/27d236203818ebf9d65ab308ed6d517c.js&quot;&gt;&lt;/script&gt;
&lt;h3 id=&quot;RP&quot;&gt;
Related Posts&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Lists: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-dictionaries-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Dictionaries: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Tuples: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html&quot; target=&quot;_blank&quot;&gt;List, Set and Dictionary Comprehensions in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions: Explained with 10 Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h3&gt;
Useful resources and references&lt;/h3&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3.7/tutorial/datastructures.html#sets&quot; target=&quot;_blank&quot;&gt;Python documentation for sets&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-5722055735942436542</guid><pubDate>Tue, 19 Mar 2019 06:56:00 +0000</pubDate><atom:updated>2019-03-30T11:51:57.257-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cheat Sheet</category><category domain="http://www.blogger.com/atom/ns#">Data types</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python Tuples: Cheat Sheet</title><description>A cheat sheet for tuples in Python. What are tuples? How are they used in Python?&lt;br /&gt;
&lt;div&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/br&gt;&lt;br /&gt;
&lt;a href=&quot;#T&quot;&gt;Jump to the cheat sheet&lt;/a&gt;
&lt;br /&gt;
&lt;div&gt;
Similar to &lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;lists&lt;/a&gt;, tuples are another example of a &#39;sequence&#39;&amp;nbsp; datatype in Python. Some key points:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;A tuple contains an ordered collection of values or items.&lt;/li&gt;
&lt;li&gt;Tuples are defined as a comma-separated list of items (usually enclosed within parenthesis).&lt;/li&gt;
&lt;li&gt;They can also be constructed using the &lt;i&gt;tuple()&lt;/i&gt;&amp;nbsp;constructor. It takes any sequence as its input.&lt;/li&gt;
&lt;li&gt;They can contain elements of the same or different data types.&lt;/li&gt;
&lt;li&gt;Items in a tuple can be accessed by unpacking or indexing.&lt;/li&gt;
&lt;li&gt;Elements of a tuple are indexed from 0 to length-1.&lt;/li&gt;
&lt;li&gt;Tuples are immutable, i.e., once the tuple is created, we cannot change its contents.&lt;/li&gt;
&lt;li&gt;We cannot assign values to elements of tuples by indexing them. Neither does it support methods like append(), insert(), delete(), etc. which are typically used for mutating collections.&lt;/li&gt;
&lt;li&gt;Tuples support &lt;i&gt;sequence unpacking,&lt;/i&gt; i.e., its elements&amp;nbsp;can be &lt;i&gt;unpacked&lt;/i&gt;&amp;nbsp;to individual variables.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;T&quot;&gt;
Tuples: Cheatsheet&lt;/h2&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/557992a80aa87895d7b02f2b2d71c763.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;h2 id=&quot;RP&quot;&gt;
Related Posts&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Lists: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Sets: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-dictionaries-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Dictionaries: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html&quot; target=&quot;_blank&quot;&gt;List, Set and Dictionary Comprehensions in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions: Explained with 10 Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2&gt;
Useful Resources and References&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences&quot; target=&quot;_blank&quot;&gt;Python documentation for tuples&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-4718715549447818418</guid><pubDate>Mon, 18 Mar 2019 06:50:00 +0000</pubDate><atom:updated>2019-03-30T11:51:47.829-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Cheat Sheet</category><category domain="http://www.blogger.com/atom/ns#">Data types</category><category domain="http://www.blogger.com/atom/ns#">List</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python Lists: Cheat Sheet</title><description>A cheat sheet for Python lists.&lt;br /&gt;
&lt;div&gt;
&lt;h2&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;/h2&gt;
&lt;/div&gt;
&lt;a href=&quot;https://www.blogger.com/blogger.g?blogID=558019147766984999#cheatsheet&quot;&gt;Jump to the cheat sheet&lt;/a&gt;
&lt;br /&gt;
&lt;div&gt;
Lists are one of the most commonly used &#39;sequence&#39; data types in Python. Following are some of the key things to know about Python lists.&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;A list contains an ordered group of values or items. These items can be of the same or different data types.&lt;/li&gt;
&lt;li&gt;Lists are initialized using square brackets &#39;[]&#39; or by using list() constructor method.&lt;/li&gt;
&lt;li&gt;We can get the length of a list using the len() method.&lt;/li&gt;
&lt;li&gt;Lists can be indexed, i.e., we can access the elements of a list using their position in the list. The first index is &#39;0&#39; and the last index is &#39;len(list_object) - 1&#39;.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;Lists are mutable, i.e., we can change their content.&lt;/li&gt;
&lt;li&gt;We can append items to a list using the append() method.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;cheatsheet&quot;&gt;
Lists: Cheatsheet&lt;/h2&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/e6a6a542cf9b77759206271cc8f700fd.js&quot;&gt;&lt;/script&gt;
&lt;/div&gt;
&lt;h2 id=&quot;RP&quot;&gt;
Related Posts&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-sets-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Sets: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-dictionaries-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Dictionaries: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-tuples-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Tuples: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html&quot; target=&quot;_blank&quot;&gt;List, Set and Dictionary Comprehensions in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehensions: Explained with 10 Examples&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2&gt;
Reference&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/tutorial/introduction.html#lists&quot; target=&quot;_blank&quot;&gt;Python3 documentation: Lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://docs.python.org/3/tutorial/datastructures.html#more-on-lists&quot; target=&quot;_blank&quot;&gt;Python3 documentation: More on lists&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-4165872506740162259</guid><pubDate>Sun, 17 Mar 2019 10:07:00 +0000</pubDate><atom:updated>2019-03-30T11:48:25.730-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">List Comprehension</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python List Comprehensions: Explained with Examples</title><description>In this post, we will go through a set of examples for list comprehensions in Python. We will start with a very basic example and gradually work our way up to more complex ones.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;h2&gt;
Table of Contents&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#PL&quot;&gt;Python lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#LC&quot;&gt;List Comprehensions&lt;/a&gt;&lt;/li&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;#E1&quot;&gt;1. Create a list using a list comprehension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E2&quot;&gt;2. List comprehension with an expression&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E3&quot;&gt;3. List comprehension with an &lt;i&gt;if &lt;/i&gt;condition&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E4&quot;&gt;4. List comprehension with an &lt;i&gt;if-else&lt;/i&gt; condition&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E5&quot;&gt;5. List comprehension with an &lt;i&gt;if-elif-else&amp;nbsp;&lt;/i&gt;ladder&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E6&quot;&gt;6. Using methods within list comprehension&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E7&quot;&gt;7. List comprehension with&amp;nbsp;&lt;i&gt;nested-if&lt;/i&gt; conditions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E8&quot;&gt;8. List comprehension equivalent of&amp;nbsp;&lt;i&gt;nested for loops&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E9&quot;&gt;9. List comprehension to flatten a list of lists&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#E10&quot;&gt;10. Nested list comprehension&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;li&gt;&lt;a href=&quot;#RP&quot;&gt;Related Posts&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;#UR&quot;&gt;Useful Resources and References&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;h2 id=&quot;PL&quot;&gt;
Python lists&lt;/h2&gt;
Before starting with the list comprehension examples, let us take a look at what lists look like and how they are created in Python. The following code snippet should help to set the basic pre-requisites before we dive into the examples.
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/7fa0b951b4a01c301d3932613b22af5e.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h2 id=&quot;LC&quot;&gt;
List Comprehensions&lt;/h2&gt;
If you are not familiar with list comprehensions, now may be a good time to take a look at my post on&amp;nbsp;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Understanding the basics of List Comprehension in Python&lt;/a&gt;. We will be following the same pattern of introducing the problem we are trying to solve, seeing how it is done with a traditional &lt;i&gt;for&lt;/i&gt; loop and then see how we can convert that &lt;i&gt;for&lt;/i&gt; loop into a list comprehension. I will include a screen recording of the transformation of &lt;i&gt;for&lt;/i&gt; loop to list comprehension so that you can understand it clearly.&lt;br /&gt;
&lt;h2 id=&quot;E1&quot;&gt;
1. Create a list using a list comprehension&lt;/h2&gt;
&lt;div&gt;
This example shows the most basic form of list comprehension. Here we will be creating a list of numbers in a specific range. We will see how it is done using a for loop and then rewrite it using a list comprehension.&lt;/div&gt;
&lt;div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/6f7f7054460ff22c413db8d3ae190cc1.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dzpwl25Z6-GIe-zMSr-KjSOrcBFX1XUe-nwk07lB-PH6rC8WTn49XIoMrDMu0dcHTtPWIrv3fNpv8k5hiypAA&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h2 id=&quot;E2&quot;&gt;
2. List comprehension with an expression&lt;/h2&gt;
&lt;div&gt;
Now let us build on the previous example by applying an operation on each of the list items. We will be creating a new list where each number is the double of the numbers in the original list.&lt;/div&gt;
&lt;div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/b7fd05dabeb1465802e11d9627d8d244.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dzYplJL5KbuiSfHRtddmfV8aYB_L3rTrx03iJS5l426SVRdFoV22XtaxZWBc4nyzWNMzCvw6cu6UWEzf1JFzQ&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h2 id=&quot;E3&quot;&gt;
3. List comprehension with an &lt;i&gt;if &lt;/i&gt;condition&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
Next, let us introduce if conditions to our list comprehension. In this case, we will create a new list which contains the squares of all the odd numbers in the original list.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/86990ee536ed8d9c82b0d01305a72514.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dzHNVHZ3bnPnuiAbt4b_XljH1ryFKO8rTfM9S88OgTRRBOzqXfV9LqVmbSwJ0NCE7pOOc7qxuMb-uP2GaiUfw&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;br /&gt;
Awesome! Now we have completed the basic forms of list comprehension, i.e., one for loop and one if condition. The upcoming examples will take you through its more advanced variations.&lt;br /&gt;
&lt;h2 id=&quot;E4&quot;&gt;
4. List comprehension with an &lt;i&gt;if-else&lt;/i&gt; condition&lt;/h2&gt;
&lt;div&gt;
If we wanted to compute different values based on two different conditions, then we would need to use an if-else block. Let&#39;s take a look at how we can create a new list with the doubles of all the even numbers and squares of all the odd numbers. Note that, in this case, the if-else condition precedes the for loop.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/59b64532762c01310c56ef4b3c0226c4.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dyBCAmU-HvmvVZoCyafwCsyAiq333F_Myr5AbW6Kdx-qLSUQgrk6idAq9YAlmNqdpMKOPUU8gAGe5i5-mxIhQ&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;h2 id=&quot;E5&quot;&gt;
5. List comprehension with an &lt;i&gt;if-elif-else&amp;nbsp;&lt;/i&gt;ladder&lt;/h2&gt;
&lt;div&gt;
Extending the previous example to an if-else ladder is quite straight forward. However, note that, in this case, we no longer use &lt;i&gt;&#39;elif condition&#39;&lt;/i&gt;, but split that to &lt;i&gt;&#39;else value if condition&#39;&lt;/i&gt;. Let&#39;s see how we can create a new list where we substitute all multiples of 2 by 0, multiples of 3(which are not multiples of 2) by 1 and leave the rest as it is.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/0c803cf7ef9f3b5322e6c0fe1b53e69b.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dxsTO8CiDA-_c_5F-DJNSibHgIxpc32jljv6owGETdZbFIB9V09tGKJDHRSX06xTw7Q9H8HlMWgsczp_N7mkg&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h2 id=&quot;E6&quot;&gt;
6. Using methods within list comprehension&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
There will be cases where we need to perform more complex computations on the list items. Squeezing all of that code into a list comprehension may make the code difficult to read and understand. Worry not, we can use methods within list comprehension. To keep it simple, in this example, we will just move the above if-else ladder into a new method and use that within our list comprehension.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/83941879d9ca4d8e41b8d12d6d57b9d9.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dx6Z6e-99AwIE0bcEkOgnwGfT9nzsRWwebNAnwirBwwkKwGHhDTfhnkVaDr1aiA6a4Iu8u6CNrcbephTScHxg&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;h2 id=&quot;E7&quot;&gt;
7. List comprehension with&amp;nbsp;&lt;i&gt;nested-if&lt;/i&gt; conditions&lt;/h2&gt;
&lt;div&gt;
Next, let us see how we can handle nested-if with a list comprehension. You can easily extend this to nested if-else conditions. But most likely, a for loop would be more readable in such cases. We will just take a simple example of finding all even multiple of 5 from a list of numbers(which is nothing but multiples of 10).&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/7d0d201f2623df7b09638515d9ba78d7.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dykytQYeEsMZHcIs1qMtRzhV-dst3VWdQZvwMSWIFqmmCJPw_kVqmst3Xo0NBxK1tyfKNXZCtv6WRPSeeUjKg&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;h2 id=&quot;E8&quot;&gt;
8. List comprehension equivalent of&amp;nbsp;&lt;i&gt;nested for loops&lt;/i&gt;&lt;/h2&gt;
&lt;/div&gt;
&lt;div&gt;
Now let&#39;s see how we can write a list comprehension equivalent for nested for loops. We will take the example of creating a list of (subtsring, string) tuples from two lists. The first is a list of substrings and the second is a list of strings to be parsed for substrings.&lt;br /&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/2b0de9a3bd67ea5ef2795dd2ef13e894.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&amp;nbsp;&lt;/h4&gt;
&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dzHihpz_5XbQ-7_yuv8TinW8xncRBJqhvPLWhodgwSSRbKCuJLI_M-LS2XeUNHgptOyg-G52GFnFo-xg06HUw&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;h2 id=&quot;E9&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
9. List comprehension to flatten a list of lists&lt;/h2&gt;
&lt;div&gt;
This is an example from the&amp;nbsp;&lt;a href=&quot;https://www.blogger.com/%3Cscript%20src=%22https://gist.github.com/ShyamaSankar/2b0de9a3bd67ea5ef2795dd2ef13e894.js%22%3E%3C/script%3E&quot; target=&quot;_blank&quot;&gt;Python3 documentation&lt;/a&gt;&amp;nbsp;which seemed a bit confusing to me at first. Let&#39;s see how that is done. Note the similarity with example 8.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/24cafba55fdd108638cdb9b73cb51251.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dzlY4bwMI4q27ThSlcFG9yqe48OxuxKHLF2kKf7aMyqIlCvPadQW6vkfFh6aa072-HsWOXPiRqFgGz0b9QQ0w&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;h2 id=&quot;E10&quot;&gt;
10. Nested list comprehension&lt;/h2&gt;
&lt;div&gt;
A nested list comprehension is essentially a list comprehension where the first expression defining the elements of a list is another list comprehension. As you can imagine, this would result in a list of lists. Let&#39;s take the example of adding two matrices.&lt;/div&gt;
&lt;h4&gt;
Code snippet&lt;/h4&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/af33dc67c8967a836bdbdaba05ec1b4f.js&quot;&gt;&lt;/script&gt;

&lt;br /&gt;
&lt;h4&gt;
Screen recording&lt;/h4&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dx5UZNGad5l4Tp5bEr7nvCDihaQ1EknGJw_Xm9cWLnI8PQPo070rltHyrtaUkgehwSRhJECQCwFLXr-F8wJ&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;

&lt;h2 id=&quot;RP&quot;&gt;
Related Posts&lt;/h2&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/python-lists-cheat-sheet.html&quot; target=&quot;_blank&quot;&gt;Python Lists: Cheat Sheet&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-set-and-dictionary-comprehensions.html&quot; target=&quot;_blank&quot;&gt;List, Set and Dictionary Comprehensions in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python List Comprehension: Understanding the Basics&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/iteration-in-python-for-while-break-and.html&quot; target=&quot;_blank&quot;&gt;Iterations in Python: The for, while, break and continue statements&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;h2 id=&quot;UR&quot;&gt;
Useful Resources and References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html&quot; target=&quot;_blank&quot;&gt;Python3 documentation for List Comprehension&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/python-list-comprehension-examples.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-558019147766984999.post-1717914805124043468</guid><pubDate>Sat, 16 Mar 2019 09:49:00 +0000</pubDate><atom:updated>2019-03-17T18:31:32.891-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">List Comprehension</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>List Comprehension in Python: Understanding the Basics</title><description>A list comprehension is a concise way of creating a new list from an iterable. It may seem a bit tricky in the beginning, but it can be your new best friend once you understand and get used to it! In this tutorial, we will look at a very basic example of list comprehension.&lt;br /&gt;
&lt;a name=&#39;more&#39;&gt;&lt;/a&gt;&lt;br /&gt;
&lt;h2&gt;
Creating a filtered list&lt;/h2&gt;
&lt;div&gt;
One of the most basic examples of a list comprehension would be filtering out elements of a list into a new list.&lt;br /&gt;
To illustrate it, let us take a look at how we would write a simple loop to filter out all even numbers from a list of numbers.&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/264728091b4f3dd031c74d59da3044b9.js&quot;&gt;&lt;/script&gt;
Using list comprehension, we would rewrite this as follows.&lt;br /&gt;
&lt;script src=&quot;https://gist.github.com/ShyamaSankar/1ac3f839f023b6765c5535d96e69c936.js&quot;&gt;&lt;/script&gt;
&lt;span style=&quot;text-align: center;&quot;&gt;Let us take a look at what we actually did here:&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;iframe allowfullscreen=&#39;allowfullscreen&#39; webkitallowfullscreen=&#39;webkitallowfullscreen&#39; mozallowfullscreen=&#39;mozallowfullscreen&#39; width=&#39;320&#39; height=&#39;266&#39; src=&#39;https://www.blogger.com/video.g?token=AD6v5dyhP7pphx9qgyzrMuczfphcja7o7fIMvkpOY1ZfodMw051e3IO6-yCGEFFAfslliYTtyErLeuxmz525EcMdrw&#39; class=&#39;b-hbp-video b-uploaded&#39; frameborder=&#39;0&#39;&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;br /&gt;
Now let us get into the step by step details of how we converted the for loop into the list comprehension:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Just as we did initially, we create a new list object &lt;i&gt;even_numbers &lt;/i&gt;using the square brackets.&lt;/li&gt;
&lt;!-- HTML generated using hilite.me --&gt;&lt;div style=&quot;background: #f8f8f8; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;&quot;&gt;
&lt;pre style=&quot;line-height: 125%; margin: 0;&quot;&gt;even_numbers &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; []
&lt;/pre&gt;
&lt;/div&gt;
&lt;li&gt;Then we define the elements of this new list as the &lt;i&gt;expression&lt;/i&gt;&amp;nbsp;which we used within &#39;&lt;i&gt;even_numbers.append()&#39;&lt;/i&gt;. In this case, since we are just filtering out certain &lt;i&gt;numbers&lt;/i&gt;, the variable &lt;i&gt;number&lt;/i&gt;&amp;nbsp;itself is the &lt;i&gt;expression.&lt;/i&gt;&lt;/li&gt;
&lt;!-- HTML generated using hilite.me --&gt;&lt;div style=&quot;background: #f8f8f8; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;&quot;&gt;
&lt;pre style=&quot;line-height: 125%; margin: 0;&quot;&gt;even_numbers &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; [number]
&lt;/pre&gt;
&lt;/div&gt;
&lt;li&gt;As you can see we have not yet defined the variable &lt;i&gt;number. &lt;/i&gt;This is done by the &lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop.&amp;nbsp;&lt;/li&gt;
&lt;!-- HTML generated using hilite.me --&gt;&lt;div style=&quot;background: #f8f8f8; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;&quot;&gt;
&lt;pre style=&quot;line-height: 125%; margin: 0;&quot;&gt;even_numbers &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; [number &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;for&lt;/span&gt; number &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;in&lt;/span&gt; numbers]
&lt;/pre&gt;
&lt;/div&gt;
Note that once this is done, even_numbers is a copy of numbers. This is a perfectly valid list comprehension with the resulting list being a copy of the original list.
&lt;li&gt;Now all that is left to do is adding the conditional.&lt;/li&gt;
&lt;!-- HTML generated using hilite.me --&gt;&lt;div style=&quot;background: #f8f8f8; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;&quot;&gt;
&lt;pre style=&quot;line-height: 125%; margin: 0;&quot;&gt;even_numbers &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; [number &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;for&lt;/span&gt; number &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;in&lt;/span&gt; numbers &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;if&lt;/span&gt; number &lt;span style=&quot;color: #666666;&quot;&gt;%&lt;/span&gt; &lt;span style=&quot;color: #666666;&quot;&gt;2&lt;/span&gt; &lt;span style=&quot;color: #666666;&quot;&gt;==&lt;/span&gt; &lt;span style=&quot;color: #666666;&quot;&gt;0&lt;/span&gt;]
&lt;/pre&gt;
&lt;/div&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div&gt;
That was not so difficult, was it! 😊&lt;br /&gt;
&lt;br /&gt;
To summarize, we can use a list comprehension instead of a traditional for loop if the loop follows the following syntax.&lt;br /&gt;
&lt;!-- HTML generated using hilite.me --&gt;&lt;br /&gt;
&lt;div style=&quot;background: #f8f8f8; border-width: 0.1em 0.1em 0.1em 0.8em; border: solid gray; overflow: auto; padding: 0.2em 0.6em; width: auto;&quot;&gt;
&lt;pre style=&quot;line-height: 125%; margin: 0;&quot;&gt;&lt;span style=&quot;color: #008800; font-style: italic;&quot;&gt;# For loop&lt;/span&gt;
new_items_list &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; []
&lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;for&lt;/span&gt; item &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;in&lt;/span&gt; items_list:
  &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;if&lt;/span&gt; condition(item):
    new_items_list&lt;span style=&quot;color: #666666;&quot;&gt;.&lt;/span&gt;append(expression(item))

&lt;span style=&quot;color: #008800; font-style: italic;&quot;&gt;# Equivalent list comprehension&lt;/span&gt;
new_items_list &lt;span style=&quot;color: #666666;&quot;&gt;=&lt;/span&gt; [expression(item) &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;for&lt;/span&gt; item &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;in&lt;/span&gt; items_list &lt;span style=&quot;color: #aa22ff; font-weight: bold;&quot;&gt;if&lt;/span&gt; condition(item)]
&lt;/pre&gt;
&lt;/div&gt;
&lt;br /&gt;
Note that we could have zero or more&amp;nbsp;&lt;i&gt;for&amp;nbsp;&lt;/i&gt;loops and&amp;nbsp;&lt;i&gt;if&amp;nbsp;&lt;/i&gt;conditions following the initial&amp;nbsp;&lt;i&gt;for&lt;/i&gt;&amp;nbsp;loop. My next blog post will discuss more complex list comprehensions.&lt;br /&gt;
&lt;br /&gt;
Thank you for visiting my blog! Feel free to comment with any corrections, suggestions, questions or feedback!&lt;/div&gt;
</description><link>https://mypythonlessons.blogspot.com/2019/03/list-comprehension-in-python.html</link><author>noreply@blogger.com (Shyama Sankar)</author><thr:total>0</thr:total></item></channel></rss>