{"id":127703,"date":"2022-08-29T20:41:00","date_gmt":"2022-08-29T20:41:00","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=3951"},"modified":"2022-08-29T20:41:00","modified_gmt":"2022-08-29T20:41:00","slug":"python-programming-tutorial-cheat-sheets","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/29\/python-programming-tutorial-cheat-sheets\/","title":{"rendered":"Python Programming Tutorial [+Cheat Sheets]"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;3951&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;5&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (5 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (5 votes) <\/div>\n<\/div>\n<p><em>(Reading time: 19 minutes)<\/em><\/p>\n<p>The purpose of this article is to help you refresh your knowledge of all the basic <a href=\"https:\/\/blog.finxter.com\/python-cheat-sheet\/\" data-type=\"post\" data-id=\"305\" target=\"_blank\" rel=\"noreferrer noopener\">Python keywords<\/a>, <a href=\"https:\/\/blog.finxter.com\/top-10-best-data-structure-cheat-sheets-in-python\/\" data-type=\"post\" data-id=\"21064\" target=\"_blank\" rel=\"noreferrer noopener\">data structures<\/a>, and <a href=\"https:\/\/blog.finxter.com\/email-academy\/\" data-type=\"page\" data-id=\"12278\" target=\"_blank\" rel=\"noreferrer noopener\">fundamentals<\/a>. I wrote it for the intermediate Python programmer who wants to reach the <a href=\"https:\/\/app.finxter.com\/learn\/computer\/science\/\" data-type=\"URL\" data-id=\"https:\/\/app.finxter.com\/learn\/computer\/science\/\" target=\"_blank\" rel=\"noreferrer noopener\">next level<\/a> of programming expertise.<\/p>\n<p><strong>The way of achieving an expert level is through studying the basics.<\/strong> <\/p>\n<p>Computer science professors usually have an extremely profound knowledge of the basics in their field. This enables them to argue from &#8220;first principles&#8221; rather than from the state-of-the-art\u2014it&#8217;s easier for them to identify research gaps because they know about the ground rules in their field rather than being blinded by the latest technology and state-of-the-art. <\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Tip<\/strong>: If you want to reach the next level in coding, take your time and study the basics carefully. <\/p>\n<p>This article provides you with the most important Python basics which serve as a foundation for more advanced topics.<\/p>\n<p>Download your <a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\">5x Python cheat sheets<\/a>, print them, and pin them to your office wall!<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/blog.finxter.com\/subscribe\/\" target=\"_blank\" rel=\"noreferrer noopener\"><img decoding=\"async\" loading=\"lazy\" width=\"791\" height=\"1024\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-791x1024.jpg\" alt=\"\" class=\"wp-image-2333\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1.jpg 791w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-232x300.jpg 232w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-768x994.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-100x129.jpg 100w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-864x1118.jpg 864w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2019\/03\/CheatSheet-Python-1-Keywords-1-1200x1553.jpg 1200w\" sizes=\"auto, (max-width: 791px) 100vw, 791px\" \/><\/a><\/figure>\n<\/div>\n<p>Click the image to register and download all Python cheat sheets.<\/p>\n<h2 id=\"keywords\">Python Keywords<\/h2>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhkOAShEryUo%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p>Like any other programming language, Python has many <em>keywords <\/em>with special meaning. For instance, <em><a href=\"https:\/\/blog.finxter.com\/how-to-check-your-python-version\/\" data-type=\"post\" data-id=\"1371\" target=\"_blank\" rel=\"noreferrer noopener\">Python 3.7<\/a><\/em> comes with 33 special keywords:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">False\nclass\nfinally is return\nNone\ncontinue\nfor\nlambda\ntry\nTrue\ndef\nfrom nonlocal while\nand del global not with\nas elif if or yield\nassert else import pass break except in raise<\/pre>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f9e9.png\" alt=\"\ud83e\udde9\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Exercise<\/strong>: Quickly glance over the list of keywords and try to explain their meaning. <\/p>\n<p>In the following, you will study the most important Python<br \/>\nkeywords with short examples.<\/p>\n<h3>Keywords: False, True<\/h3>\n<p>These keywords represent the only two data values from the Boolean data type.<\/p>\n<p>In Python, Boolean and integer data types are closely related: the Boolean data type internally uses integer values. Per default, the Boolean value <code>False<\/code> is represented by integer 0, and the Boolean value <code>True<\/code> is represented by integer 1.&nbsp;<\/p>\n<p>The following code snippet gives you an example of these two Boolean keywords.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">x = 1 > 2\nprint(x)\n# False y = 2 > 1\nprint(y)\n# True\n<\/pre>\n<p>After evaluating the given expressions, variable name <code>x<\/code> refers to the Boolean value <code>False<\/code> , and variable <code>y<\/code> refers to the Boolean value <code>True<\/code>.<\/p>\n<h3>Keywords: and, or, not<\/h3>\n<p>These keywords represent basic logical<br \/>\noperators.<\/p>\n<ul>\n<li><strong>Keyword <code>and<\/code><\/strong>: The expression <code>x and y<\/code> evaluates to <code>True<\/code> if both values <code>x<\/code> and <code>y<\/code> evaluate to <code>True<\/code>. If one or both evaluate to <code>False<\/code>, the overall expression becomes <code>False<\/code>.<\/li>\n<li><strong>Keyword <code>or<\/code><\/strong>: The expression <code>x or y<\/code> evaluates to <code>True<\/code> if <code>x<\/code> is <code>True<\/code> or <code>y<\/code> is <code>True<\/code> (or both are <code>True<\/code>). If one of those is <code>True<\/code>, the overall expression becomes <code>True<\/code>.<\/li>\n<li><strong>Keyword <code>not<\/code><\/strong>: The expression <code>not x<\/code> evaluates to <code>True<\/code> if <code>x<\/code> evaluates to <code>False<\/code>.<\/li>\n<\/ul>\n<p>Consider the following Python code example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">x, y = True, False print((x or y) == True)\n# True print((x and y) == False)\n# True print((not y) == True)\n# True <\/pre>\n<p>By using these three operations\u2014<code>and<\/code>, <code>or<\/code>, and <code>not<\/code>\u2014you can express all logical expressions you&#8217;ll ever need.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> Learn More: The following three tutorials guide you into those crucial Python logical operators:<\/p>\n<ul>\n<li><a href=\"https:\/\/blog.finxter.com\/python-and-operator\/\" data-type=\"post\" data-id=\"31722\" target=\"_blank\" rel=\"noreferrer noopener\">Python <code>and<\/code> Operator<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-or-operator\/\" data-type=\"post\" data-id=\"31848\" target=\"_blank\" rel=\"noreferrer noopener\">Python <code>or<\/code> Operator<\/a><\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/python-not-operator\/\" data-type=\"post\" data-id=\"32000\" target=\"_blank\" rel=\"noreferrer noopener\">Python <code>not<\/code> Operator<\/a><\/li>\n<\/ul>\n<h3>Keywords: if, else, elif<\/h3>\n<p>Algorithms are often compared to cooking recipes. Imagine a cooking recipe that consists only of a sequential list of commands: fill water into a pot, add the salt, add the rice, get rid of the water, and serve the rice. <\/p>\n<p>Strictly speaking, without a <em>conditional execution<\/em>, the sequence of commands would take only a few seconds to execute and the rice would not be ready for sure. <\/p>\n<p>For example, you would fill in water, salt, and rice and immediately get rid of the water without waiting for the water to be hot and the rice to be soft. <\/p>\n<p>We need to respond in a different way to different circumstances: we need to remove the water from the pot only <strong>if <\/strong>the rice is soft, and we need to put in the rice <strong>if <\/strong>the water is hot. <\/p>\n<p>It&#8217;s almost impossible to write programs in a way that anticipates what happens in the real world in a deterministic manner.<\/p>\n<p>Instead, we need to write programs that respond differently if different conditions are met. This is precisely why we need conditional execution with the keywords <strong><code>if<\/code><\/strong>, <strong><code>else<\/code><\/strong>, and <g class=\"gr_ gr_6 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling\" id=\"6\" data-gr-id=\"6\"><strong><code>elif<\/code><\/strong><\/g>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">x = int(input(\"your value: \"))\nif x > 3: print(\"Big\")\nelif x == 3: print(\"Medium\")\nelse: print(\"Small\")<\/pre>\n<p>The code snippet first takes the <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-input-function\/\" data-type=\"post\" data-id=\"24632\" target=\"_blank\">user input<\/a>, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-int-function\/\" data-type=\"post\" data-id=\"22715\" target=\"_blank\">converts it into an integer<\/a>, and assign it to variable <code>x<\/code>. <\/p>\n<p>It then tests the variable value whether it is larger than, equal to, or smaller than the value 3. In other words, the code responds to real-world input that is unpredictable in a differentiated manner.<\/p>\n<h3>Keywords: for, while<\/h3>\n<p>Computers are extremely fast\u2014they execute billions of instructions per second. <\/p>\n<p>Now imagine a world without a way of executing the same code snippet multiple times (with modified input). A program that runs only for a day would have to consist of trillions of lines of code (otherwise it would quickly run out of code to be executed). And the code would look like a mess because it would be highly redundant and not readable. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Resource<\/strong>: <a href=\"https:\/\/blog.finxter.com\/tips-to-write-clean-code\/\" data-type=\"post\" data-id=\"17059\" target=\"_blank\" rel=\"noreferrer noopener\">How to Write Clean Code?<\/a><\/p>\n<p>To allow for repeated execution of similar code snippets, Python (like any other major programming language) allows for two types of <a href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"post\" data-id=\"4596\" target=\"_blank\" rel=\"noreferrer noopener\">loops<\/a>: <strong>for loops<\/strong> and <strong>while loops<\/strong>. <\/p>\n<p>This way, you can easily write a program consisting only of two lines of code that executes forever. It&#8217;s hard to do this without loops&#8211;the only alternative is <a href=\"https:\/\/blog.finxter.com\/recursion\/\" data-type=\"post\" data-id=\"3941\" target=\"_blank\" rel=\"noreferrer noopener\">recursion<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># For loop declaration\nfor i in [0, 1, 2]: print(i) '''\n0\n1\n2 ''' # While loop - same semantics\nj = 0\nwhile j &lt; 3: print(j) j = j + 1 '''\n0\n1\n2 '''\n<\/pre>\n<p>Both loop variants achieve the same thing: they <a href=\"https:\/\/blog.finxter.com\/python-print\/\" data-type=\"post\" data-id=\"20731\" target=\"_blank\" rel=\"noreferrer noopener\">print<\/a> the integers 0, 1, and 2 to the shell. <\/p>\n<p>The loops accomplish this in two different ways. <\/p>\n<ul>\n<li>The <code>for<\/code> loop repeatedly executes the loop body by declaring a loop variable <code>i<\/code> that iteratively takes on all values in the list <code>[0, 1, 2]<\/code>. <\/li>\n<li>The <code>while<\/code> loop executes the loop body as long as a certain condition is met\u2014in our case <code>j &lt; 3<\/code>.<\/li>\n<\/ul>\n<h3>Keyword: break<\/h3>\n<p>There are two fundamental ways of terminating a loop: (i) define a loop condition that evaluates to <code>False<\/code>, or (ii) use the keyword <code>break<\/code> at the exact position in the loop body.<\/p>\n<p>The following code snippet shows an example of the latter.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">while True: break # no infinite loop print(\"hello world\")\n# hello world<\/pre>\n<p>We create a while loop with a loop condition that will always evaluate to <code>True<\/code>. <\/p>\n<p>For example, this is common practice when developing <a href=\"https:\/\/blog.finxter.com\/python-one-liner-webserver\/\" data-type=\"post\" data-id=\"8635\">w<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-one-liner-webserver\/\" data-type=\"post\" data-id=\"8635\" target=\"_blank\">e<\/a><a href=\"https:\/\/blog.finxter.com\/python-one-liner-webserver\/\" data-type=\"post\" data-id=\"8635\">b servers<\/a> that repeat the following procedure forever: wait for a new web request and serve the request. <\/p>\n<p>However, in some cases, you still want to terminate the loop prematurely. <\/p>\n<p>In the webserver example, you would stop serving files for security reasons when your server detects that it is under attack. In these cases, you can use the keyword <code>break<\/code> to immediately stop the loop and execute the code that follows.<\/p>\n<p>In the example, the code executes <code>print(\"hello world\")<\/code><strong> <\/strong>after the loop ends prematurely.<\/p>\n<h3>Keyword: continue<\/h3>\n<p>The <code>break<\/code> statement is not the only statement that allows you to modify the execution flow of Python loops. <\/p>\n<p>It is also possible to force the Python interpreter to skip certain areas in the loop while <strong>not <\/strong>ending it prematurely. <\/p>\n<p>In the previously considered web server example, you may just want to skip malicious web requests instead of halting the server completely. This can be achieved using the <code>continue<\/code> statement that finishes the current loop iteration and brings the execution flow back to the loop condition.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">while True: continue print(\"43\") # dead code <\/pre>\n<p>The code executes forever without executing the <code>print<\/code> statement once. The reason is that the <code>continue<\/code> statement finishes the current loop iteration. <\/p>\n<p>The effect of using the <code>continue<\/code> statement in this way is that there exists <g class=\"gr_ gr_8 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep\" id=\"8\" data-gr-id=\"8\">dead<\/g> code that will never be executed. <\/p>\n<p>That&#8217;s why the <code>continue<\/code> statement (as well as the <code>break<\/code> statement) is commonly used under a certain condition by using a conditional if-else environment.<\/p>\n<h3>Keyword: in<\/h3>\n<p>The membership operator, i.e., <code>in<\/code> keyword, checks whether a certain element exists in a given sequence or <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\" rel=\"noreferrer noopener\">container type<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(42 in [2, 39, 42])\n# True print(\"21\" in {\"2\", \"39\", \"42\"})\n# False\n<\/pre>\n<p>The code <g class=\"gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling\" id=\"8\" data-gr-id=\"8\">sni<\/g>ppet shows that the keyword <code>in<\/code> can be used to test the membership of an integer value 42 in a <a href=\"https:\/\/blog.finxter.com\/how-to-convert-an-integer-list-to-a-float-list-in-python-2\/\" data-type=\"post\" data-id=\"27689\" target=\"_blank\" rel=\"noreferrer noopener\">list of integer<\/a> values or to test the membership of a string value <code>\"21\"<\/code> in a <a href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" data-type=\"post\" data-id=\"1908\" target=\"_blank\" rel=\"noreferrer noopener\">set<\/a> of strings.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-membership-in-operator\/\" data-type=\"post\" data-id=\"34005\" target=\"_blank\" rel=\"noreferrer noopener\">The Membership Operator in Python<\/a><\/p>\n<h3>Keyword: is<\/h3>\n<p>Beginners in Python are often confused about the exact meaning of the keyword <code>is<\/code>. <\/p>\n<p>However, if you take the time to properly understand it now, you won&#8217;t belong to this group for long. The keyword simply checks whether both variables refer to the same object in memory.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">y = x = 3 print(x is y)\n# True print([3] is [3])\n# False\n<\/pre>\n<p>If you <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list\/\" data-type=\"post\" data-id=\"10436\" target=\"_blank\" rel=\"noreferrer noopener\">create two lists<\/a>\u2014even if they contain the same elements\u2014they still refer to two different list objects in memory. Modifying one list object does not affect the other list object. <\/p>\n<p>We say that lists are <em><a href=\"https:\/\/blog.finxter.com\/mutable-vs-immutable-objects-in-python\/\" data-type=\"post\" data-id=\"204090\" target=\"_blank\" rel=\"noreferrer noopener\">mutable<\/a><\/em> because they can be modified after creation. Therefore, if you check whether one list refers to the same object in memory, the result is <code>False<\/code>. <\/p>\n<p>However, integer values are <em><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-mutable-vs-immutable-objects-in-python\/\" data-type=\"post\" data-id=\"66189\" target=\"_blank\">immutable<\/a><\/em>, so there is no risk of one variable changing the object which will then accidentally change all other variables. <\/p>\n<p>The reason is that you cannot change the integer object 3\u2014trying it will only create a new integer object and leave the old one unmodified.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-is-operator\/\" data-type=\"post\" data-id=\"33954\" target=\"_blank\" rel=\"noreferrer noopener\">The <code>is<\/code> Operator in Python<\/a><\/p>\n<h3>Keyword: return<\/h3>\n<p>The keyword <code>return<\/code> <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-do-i-return-multiple-values-from-a-function\/\" data-type=\"post\" data-id=\"308875\" target=\"_blank\">terminates<\/a> the execution of a function and passes the flow of execution to the caller of the function. An optional value after the <code>return<\/code> keyword specifies the function result.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def appreciate(x, percentage): return x + x * percentage \/ 100 print(appreciate(10000, 5))\n# 10500.0<\/pre>\n<p>We create a function <code>appreciate()<\/code> that calculates how much a given investment appreciates at a given percentage of return. <\/p>\n<p>To this end, we use the keyword <code>return<\/code> to specify the result of the function as the sum of the original investment and the nominal return in one unit of time. The return value of the function <code>appreciate()<\/code> is of type <a href=\"https:\/\/blog.finxter.com\/python-float-function\/\" data-type=\"post\" data-id=\"22782\" target=\"_blank\" rel=\"noreferrer noopener\">float<\/a>.<\/p>\n<h3>Keyword: None<\/h3>\n<p>The keyword <code>None<\/code> is a Python constant with the meaning <strong><em>&#8220;the absence of a value&#8221;<\/em><\/strong>. <\/p>\n<p>Other <a href=\"https:\/\/blog.finxter.com\/21-most-profitable-programming-languages-in-2023\/\" data-type=\"post\" data-id=\"404278\" target=\"_blank\" rel=\"noreferrer noopener\">programming languages<\/a> such as <a href=\"https:\/\/blog.finxter.com\/java-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"217907\" target=\"_blank\" rel=\"noreferrer noopener\">Java<\/a> use the value <code>null<\/code> instead. But the term null often confuses beginners assuming it&#8217;s equal to the integer value 0.<\/p>\n<p>Instead, Python uses the keyword <code>None<\/code> to indicate that it&#8217;s a different value than any numerical value for zero, an <a href=\"https:\/\/blog.finxter.com\/how-to-create-an-empty-list-in-python\/\" data-type=\"post\" data-id=\"453870\" target=\"_blank\" rel=\"noreferrer noopener\">empty list<\/a>, or an empty string. <\/p>\n<p>An interesting fact is that the value <code>None<\/code> is of its own data type.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def f(): x = 2 print(f() is None)\n# True print(\"\" == None)\n# False print(0 == None)\n# False\n<\/pre>\n<p>The code snippet shows several examples of the <code>None<\/code> data value (and what it is not). If you don&#8217;t define a return value for a function, the default return value is <code>None<\/code>. <\/p>\n<p>However, the value <code>None<\/code> is different from the empty string or the numerical zero value.<\/p>\n<h3>Keyword: lambda<\/h3>\n<p>The keyword <code>lambda<\/code> is used to define <a href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" data-type=\"post\" data-id=\"2701\" target=\"_blank\" rel=\"noreferrer noopener\">lambda functions<\/a> in Python. Lambda functions are anonymous functions that are not defined in the namespace (roughly speaking: they have no names). <\/p>\n<p>The syntax is:<\/p>\n<p><strong><code>lambda &lt;arguments&gt; : &lt;return expression&gt;<\/code><\/strong><\/p>\n<p>The lambda function can have one or multiple arguments (comma-separated). After the colon (<code>:<\/code>), you define the return expression that may (or may not) use the defined argument. It can be any expression or even another function. <\/p>\n<p>Lambda functions are very important in Python. You&#8217;ll see them a lot in practical code projects: for example to make code shorter and more concise, or to create arguments of various Python functions (such as <code><a href=\"https:\/\/blog.finxter.com\/python-map\/\" data-type=\"post\" data-id=\"242\" target=\"_blank\" rel=\"noreferrer noopener\">map()<\/a><\/code> or <code><a href=\"https:\/\/blog.finxter.com\/about-guidos-fate-of-reduce-in-python-3000\/\" data-type=\"post\" data-id=\"4374\" target=\"_blank\" rel=\"noreferrer noopener\">reduce()<\/a><\/code>). <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print((lambda x: x + 3)(3))\n# 6<\/pre>\n<p>Consider the code. <\/p>\n<p>First, we create a lambda function that takes value <code>x<\/code> and returns the result of the expression <code>x + 3<\/code>. <g class=\"gr_ gr_9 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace\" id=\"9\" data-gr-id=\"9\">The result<\/g> is a function object that can be called like any other function. Because of its semantics, we denote this function as <g class=\"gr_ gr_10 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep\" id=\"10\" data-gr-id=\"10\">incrementor<\/g> function. <\/p>\n<p>Second, when calling this incrementor function with the argument <code>x=3<\/code>, the result is the integer value 6. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/a-simple-introduction-of-the-lambda-function-in-python\/\" data-type=\"post\" data-id=\"2701\" target=\"_blank\" rel=\"noreferrer noopener\">Python Lambda Function Simple Guide<\/a><\/p>\n<h2 id=\"basic-data-structures\">Python Basic Data Structures<\/h2>\n<p>At this point, you&#8217;ve learned about the Python keywords which I view as the bare minimum every Python coder must know. <\/p>\n<p>However, writing code is more than using keywords correctly. Source code operates on data. But data can be represented in various ways\u2014a thorough understanding of data structures is one of the most fundamental skills you can acquire as a programmer. <\/p>\n<p>It will help you in every single of your future endeavors\u2014no matter whether you create <a href=\"https:\/\/academy.finxter.com\/university\/ml-project-classifying-star-wars-lego-images\/\" data-type=\"URL\" data-id=\"https:\/\/academy.finxter.com\/university\/ml-project-classifying-star-wars-lego-images\/\" target=\"_blank\" rel=\"noreferrer noopener\">machine learning projects<\/a>, work on large codebases, set up and manage websites, or write <a href=\"https:\/\/blog.finxter.com\/cheat-sheet-6-pillar-machine-learning-algorithms\/\" data-type=\"post\" data-id=\"2613\">algorithms<\/a>. <\/p>\n<p>Data structures are fundamental to those areas.<\/p>\n<h3>The Boolean Data Type<\/h3>\n<p>A variable of type Boolean can only take two values\u2014either <code>True<\/code> or <code>False<\/code>. You have already studied both keywords above.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">## 1. Boolean Operations\nx, y = True, False print(x and not y)\n# True print(not x and y or x)\n# True ## 2. If condition evaluates to False\nif None or 0 or 0.0 or '' or [] or {} or set(): print(\"Dead code\") # Not reached\n<\/pre>\n<p>The code snippet shows two important points: <\/p>\n<ul>\n<li>First, Boolean operators are ordered by <a href=\"https:\/\/blog.finxter.com\/python-operator-precedence\/\" data-type=\"post\" data-id=\"34113\" target=\"_blank\" rel=\"noreferrer noopener\">priority<\/a>\u2014the operator <code>not<\/code> has the highest priority, followed by the operator <code>and<\/code>, followed by the operator <code>or<\/code>. <\/li>\n<li>Second, the following values are evaluated to the Boolean value <code>False<\/code>: the keyword <code>None<\/code>, the integer value <code>0<\/code>, the float value <code>0.0<\/code>, empty strings, or <a href=\"https:\/\/blog.finxter.com\/how-to-create-an-empty-list-in-python\/\" data-type=\"post\" data-id=\"453870\" target=\"_blank\" rel=\"noreferrer noopener\">empty<\/a> container types.<\/li>\n<\/ul>\n<h3>Numerical Data Types<\/h3>\n<p>The two most important numerical data types are integer and float. <\/p>\n<ul>\n<li>An integer is a positive or negative number without <g class=\"gr_ gr_7 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"7\" data-gr-id=\"7\">floating point<\/g> (for example 3). <\/li>\n<li>A float is a positive or negative number with <a href=\"https:\/\/blog.finxter.com\/how-to-create-high-precision-data-types\/\" data-type=\"post\" data-id=\"455227\" target=\"_blank\" rel=\"noreferrer noopener\"><g class=\"gr_ gr_8 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace\" id=\"8\" data-gr-id=\"8\">floating point<\/g> precision<\/a> (for example 3.14159265359). <\/li>\n<\/ul>\n<p>Python offers a wide variety of built-in numerical operations, as well as functionality to <a href=\"https:\/\/blog.finxter.com\/how-to-convert-an-integer-list-to-a-float-list-in-python-2\/\" data-type=\"post\" data-id=\"27689\" target=\"_blank\" rel=\"noreferrer noopener\">convert<\/a> between those numerical data types. <\/p>\n<p>Study the examples carefully to master these highly important numerical operations.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">## Arithmetic Operations\nx, y = 3, 2\nprint(x + y) # = 5\nprint(x - y) # = 1\nprint(x * y) # = 6\nprint(x \/ y) # = 1.5\nprint(x \/\/ y) # = 1\nprint(x % y) # = 1\nprint(-x) # = -3\nprint(abs(-x)) # = 3\nprint(int(3.9)) # = 3\nprint(float(3)) # = 3.0\nprint(x ** y) # = 9<\/pre>\n<p>Most of the operators are self-explaining. Note that the <strong><code>\/\/<\/code> <\/strong>operator performs <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-integer-division\/\" data-type=\"post\" data-id=\"91\" target=\"_blank\">integer division<\/a>. The result is an integer value that is rounded toward the smaller integer number (for example <strong><code>3 \/\/ 2 == 1<\/code><\/strong>).<\/p>\n<h3>The String Data Type<\/h3>\n<p>Python strings are sequences of characters. Strings are <a href=\"https:\/\/blog.finxter.com\/mutable-vs-immutable-objects-in-python\/\" data-type=\"post\" data-id=\"204090\" target=\"_blank\" rel=\"noreferrer noopener\">immutable<\/a> so they cannot be changed, once created. <\/p>\n<p>There are five main ways to create strings:<\/p>\n<ul>\n<li>Single quotes: <code>'Yes'<\/code>.<\/li>\n<li>Double quotes: <code>\"Yes\"<\/code>.<\/li>\n<li>Triple quotes (for <a href=\"https:\/\/blog.finxter.com\/multi-line-strings\/\" data-type=\"post\" data-id=\"215\" target=\"_blank\" rel=\"noreferrer noopener\">multiline string<\/a>): <code>'''Yes''''<\/code> or <code>\"\"\"Yes\"\"\"<\/code>.<\/li>\n<li>The <a href=\"https:\/\/blog.finxter.com\/python-str-function\/\" data-type=\"post\" data-id=\"23735\" target=\"_blank\" rel=\"noreferrer noopener\">string method<\/a>: <code>str(5) == '5'<\/code> is <code>True<\/code>.<\/li>\n<li><a href=\"https:\/\/blog.finxter.com\/daily-python-puzzle-string-concatenation\/\" data-type=\"post\" data-id=\"93\" target=\"_blank\" rel=\"noreferrer noopener\">Concatenation<\/a>: <code>'Py' + 'thon'<\/code> becomes <code>'Python'<\/code>.<\/li>\n<\/ul>\n<p>While there are other ways, these are the five most commonly<br \/>\nused. <\/p>\n<p>Oftentimes, you want to explicitly use <a href=\"https:\/\/blog.finxter.com\/how-to-eliminate-all-the-whitespace-from-a-string\/\" data-type=\"post\" data-id=\"14577\" target=\"_blank\" rel=\"noreferrer noopener\">whitespace characters<\/a> in strings. These are the most important ones: the newline character <code>'\\n'<\/code>, the space character <code>'\\s'<\/code>, and the tab character <code>'\\t'<\/code>. <\/p>\n<p>The following code snippet shows the most important string methods.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">## Most Important String Methods\ny = \" This is lazy\\t\\n \" print(y.strip())\n# Remove Whitespace: 'This is lazy' print(\"DrDre\".lower())\n# Lowercase: 'drdre' print(\"attention\".upper())\n# Uppercase: 'ATTENTION' print(\"smartphone\".startswith(\"smart\"))\n# True print(\"smartphone\".endswith(\"phone\"))\n# True print(\"another\".find(\"other\"))\n# Match index: 2 print(\"cheat\".replace(\"ch\", \"m\"))\n# meat print(','.join([\"F\", \"B\", \"I\"]))\n# F,B,I print(len(\"Rumpelstiltskin\"))\n# String length: 15 print(\"ear\" in \"earth\")\n# Contains: True\n<\/pre>\n<p>This non-exclusive list of string methods shows that the string data type is very powerful in Python and you can solve many common string problems with built-in Python functionality. <\/p>\n<p>If in doubt about how to achieve a certain result regarding string problems, consult the following resource to learn about all built-in string methods.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-string-methods\/\" data-type=\"post\" data-id=\"25974\">Python String Methods<\/a><\/p>\n<h2 id=\"container-data-structures\">Python Container Data Structures<\/h2>\n<p>In the last section, you&#8217;ve learned about the basic Python data types. <\/p>\n<p>But Python also ships with so-called container data types that handle <strong><em>complex <\/em><\/strong>operations efficiently while being easy to use.<\/p>\n<h3>List<\/h3>\n<p>The list is a container data type that stores a sequence of elements. Unlike strings, lists are mutable. This means that you can modify them at runtime. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\" rel=\"noreferrer noopener\">Python List Ultimate Guide<\/a><\/p>\n<p>The use of the list data type is best described with a series of examples:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">l = [1, 2, 2]\nprint(len(l))\n# 3\n<\/pre>\n<p>This code snippet shows how to <a href=\"https:\/\/blog.finxter.com\/how-to-create-a-python-list-of-size-n\/\" data-type=\"post\" data-id=\"10466\" target=\"_blank\" rel=\"noreferrer noopener\">create a list<\/a> and how to populate it with three integer elements. You can also see that some elements may arise multiple times in a single list. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: The <code><a href=\"https:\/\/blog.finxter.com\/python-len\/\" data-type=\"post\" data-id=\"22386\" target=\"_blank\" rel=\"noreferrer noopener\">len()<\/a><\/code> function returns the number of elements in a list.<\/p>\n<h4>Adding Elements<\/h4>\n<p>There are three common ways of <a href=\"https:\/\/blog.finxter.com\/add-elements-to-list-python\/\" data-type=\"post\" data-id=\"9030\" target=\"_blank\" rel=\"noreferrer noopener\">adding<\/a> elements to a list: <code><a href=\"https:\/\/blog.finxter.com\/pandas-dataframe-append-method\/\" data-type=\"post\" data-id=\"343998\" target=\"_blank\" rel=\"noreferrer noopener\">append<\/a><\/code>, <code><a href=\"https:\/\/blog.finxter.com\/python-list-insert-method\/\" data-type=\"post\" data-id=\"6758\" target=\"_blank\" rel=\"noreferrer noopener\">insert<\/a><\/code>, or <a href=\"https:\/\/blog.finxter.com\/python-list-concatenation-add-vs-inplace-add-vs-extend\/\" data-type=\"post\" data-id=\"8676\" target=\"_blank\" rel=\"noreferrer noopener\">list concatenation<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># 1. Append\nl = [1, 2, 2]\nl.append(4)\nprint(l)\n# [1, 2, 2, 4] # 2. Insert\nl = [1, 2, 4]\nl.insert(2,2)\nprint(l)\n# [1, 2, 2, 4] # 3. List Concatenation\nprint([1, 2, 2] + [4])\n# [1, 2, 2, 4]\n<\/pre>\n<p>All operations generate the same list <code>[1, 2, 2, 4]<\/code> but the <code>append()<\/code> operation is the fastest because it neither has to traverse the list to insert an element at the correct position (such as <code>insert<\/code>), nor create a new list out of two sublists (such as <em>list concatenation<\/em>). <\/p>\n<p>Note that a fourth method is <code><a href=\"https:\/\/blog.finxter.com\/python-list-extend\/\" data-type=\"post\" data-id=\"6741\" target=\"_blank\" rel=\"noreferrer noopener\">extend()<\/a><\/code><strong> <\/strong>which allows you to append multiple elements to the given list in an efficient manner.<\/p>\n<h4>Removing Elements<\/h4>\n<p>Removing an element <code>x<\/code> from a list can be easily achieved using the list method <code><a href=\"https:\/\/blog.finxter.com\/how-to-remove-a-list-element-by-value-in-python\/\" data-type=\"post\" data-id=\"198814\" target=\"_blank\" rel=\"noreferrer noopener\">list.remove(x)<\/a><\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">l = [1, 2, 2, 4]\nl.remove(1)\nprint(l)\n# [2, 2, 4]\n<\/pre>\n<p>Note that the method operates on the list object itself\u2014no new<br \/>\nlist is created.<\/p>\n<h4>Reversing Lists<\/h4>\n<p>You can reverse the order of the list elements using the method <code><a href=\"https:\/\/blog.finxter.com\/python-list-reverse\/\" data-type=\"post\" data-id=\"6877\" target=\"_blank\" rel=\"noreferrer noopener\">list.reverse()<\/a><\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">l = [1, 2, 2, 4]\nl.reverse()\nprint(l)\n# [4, 2, 2, 1]\n<\/pre>\n<p>Much like the method to remove an element from a list, reversing the<br \/>\nlist modifies the original list object and does not merely create a new list<br \/>\nobject.<\/p>\n<h4>Sorting Lists<\/h4>\n<p>You can sort the list elements using the method <code><a href=\"https:\/\/blog.finxter.com\/python-list-sort\/\" data-type=\"post\" data-id=\"7176\" target=\"_blank\" rel=\"noreferrer noopener\">list.sort()<\/a><\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">l = [2, 1, 4, 2]\nl.sort()\nprint(l)\n# [1, 2, 2, 4]\n<\/pre>\n<p>Again, sorting the list modifies the original list object. <\/p>\n<p>The resulting list is sorted in an ascending manner. <\/p>\n<p>You can also <a href=\"https:\/\/blog.finxter.com\/python-list-sort-key\/\" data-type=\"post\" data-id=\"7306\" target=\"_blank\" rel=\"noreferrer noopener\">specify a key function<\/a> and pass it as the parameter <code>key<\/code> to the <code>sort()<\/code> method to customize the sorting behavior. This way, you can also sort lists of custom objects (for example, sort a list of customer objects regarding their age). <\/p>\n<p>The <code>key<\/code> function simply transforms one list element into an element that is sortable (such as an integer, float, or string element). <\/p>\n<h4>Indexing List Elements<\/h4>\n<p>You can determine the index of a specified list element <code>x<\/code> using the method <code>list.index(x)<\/code>. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print([2, 2, 4].index(2))\n# 0 print([2, 2, 4].index(2,1))\n# 1\n<\/pre>\n<p>The method<strong> <\/strong><code>index(x)<\/code><strong> <\/strong>finds the first occurrence of the element <code>x<\/code> in the list and returns its index. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\" rel=\"noreferrer noopener\">A Simple Guide to Python Lists<\/a><\/p>\n<h3>Stack<\/h3>\n<p>The <a href=\"https:\/\/en.wikipedia.org\/wiki\/Stack_(abstract_data_type)\" data-type=\"URL\" data-id=\"https:\/\/en.wikipedia.org\/wiki\/Stack_(abstract_data_type)\" target=\"_blank\" rel=\"noreferrer noopener\">stack data structure<\/a> is a natural way of storing data items. Much like an unstructured person handles their paperwork: first in, first out. <\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"439\" height=\"659\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-98.png\" alt=\"\" class=\"wp-image-629231\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-98.png 439w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-98-200x300.png 200w\" sizes=\"auto, (max-width: 439px) 100vw, 439px\" \/><\/figure>\n<\/div>\n<p>Every new paper is placed at the top of a stack of papers. When working through the stack, they remove the topmost paper from the stack. As a result, the paper at the bottom never sees the daylight. <\/p>\n<p>While this application does not seem to be a favorable way of using the stack data structure, the stack is still an extremely important fundamental data structure in <a href=\"https:\/\/blog.finxter.com\/computer-science-research-scientist\/\" data-type=\"post\" data-id=\"346253\" target=\"_blank\" rel=\"noreferrer noopener\">computer science<\/a> used in operating system management, algorithms, syntax parsing, and <a href=\"https:\/\/blog.finxter.com\/python-backtracking-a-helpful-guide-with-video\/\" data-type=\"post\" data-id=\"170273\" target=\"_blank\" rel=\"noreferrer noopener\">backtracking<\/a>.<\/p>\n<p>Python lists can be used intuitively as stacks via the two list operations <code><a href=\"https:\/\/blog.finxter.com\/python-list-append\/\" data-type=\"post\" data-id=\"6605\" target=\"_blank\" rel=\"noreferrer noopener\">append()<\/a><\/code> and <code><a href=\"https:\/\/blog.finxter.com\/python-list-pop\/\" data-type=\"post\" data-id=\"6853\" target=\"_blank\" rel=\"noreferrer noopener\">pop()<\/a><\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">stack = [3]\nstack.append(42) # [3, 42]\nstack.pop() # 42 (stack: [3])\nstack.pop() # 3 (stack: [])\n<\/pre>\n<p>Due to the efficiency of the list implementation, there is usually no need to import external stack libraries.<\/p>\n<h3>Set<\/h3>\n<p>The set data structure is one of the basic collection data types in Python and many other <a href=\"https:\/\/blog.finxter.com\/best-programming-languages-to-start-freelancing-in-2020\/\" data-type=\"post\" data-id=\"14208\" target=\"_blank\" rel=\"noreferrer noopener\">programming languages<\/a>. There are even popular languages for <a href=\"https:\/\/blog.finxter.com\/distributed-systems-engineer\/\" data-type=\"post\" data-id=\"359888\" target=\"_blank\" rel=\"noreferrer noopener\">distributed computing<\/a> that focus almost exclusively on <a href=\"https:\/\/blog.finxter.com\/python-set-methods\/\" data-type=\"post\" data-id=\"27963\" target=\"_blank\" rel=\"noreferrer noopener\">set operations<\/a> (like <a href=\"https:\/\/blog.finxter.com\/mapreduce\/\" data-type=\"post\" data-id=\"387\" target=\"_blank\" rel=\"noreferrer noopener\">MapReduce<\/a> or <a href=\"https:\/\/blog.finxter.com\/apache-spark-developer-income-and-opportunity\/\" data-type=\"post\" data-id=\"259597\" target=\"_blank\" rel=\"noreferrer noopener\">Apache Spark<\/a>) as programming primitives. <\/p>\n<p>So what is a set exactly?<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2139.png\" alt=\"\u2139\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Definition<\/strong>: A set is an unordered collection of unique elements.<\/p>\n<p>Let\u2019s break this definition into its main pieces.<\/p>\n<p>(1) <strong>Collection<\/strong>: A set is a collection of elements like a list or a tuple. <\/p>\n<p>The collection consists of either primitive elements (e.g. integers, floats, strings), or complex elements (e.g. objects, tuples). <\/p>\n<p>However, all data types must be <a href=\"https:\/\/blog.finxter.com\/python-hash-function\/\" data-type=\"post\" data-id=\"24483\" target=\"_blank\" rel=\"noreferrer noopener\">hashable<\/a> (a hash value of an object does never change and is used to compare the object to other objects). <\/p>\n<p>Let\u2019s have a look at an example.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">hero = \"Harry\"\nguide = \"Dumbledore\"\nenemy = \"Lord V.\"\nprint(hash(hero))\n# 6175908009919104006 print(hash(guide))\n# -5197671124693729851 ## Can we create a set of strings?\ncharacters = {hero, guide, enemy}\nprint(characters)\n# {'Lord V.', 'Dumbledore', 'Harry'} ## Can we create a set of lists?\nteam_1 = [hero, guide]\nteam_2 = [enemy]\nteams = {team_1, team_2}\n# TypeError: unhashable type: 'list'\n<\/pre>\n<p>As you can see, we can create a set of strings because strings are hashable. But we cannot create a set of lists because lists are <a href=\"https:\/\/blog.finxter.com\/how-to-fix-typeerror-unhashable-type-list\/\" data-type=\"post\" data-id=\"465745\" target=\"_blank\" rel=\"noreferrer noopener\">unhashable<\/a>. <\/p>\n<p>The reason is that lists are <strong><em>mutable<\/em><\/strong>: you can change a list by appending or removing elements. If you change the list data type, the hash value changes (it is calculated based on the content of the list). This violates the above definition (the hash value does not change). As mutable data types are not hashable, you cannot use them in sets.<\/p>\n<p>(2) <strong>Unordered<\/strong>: Unlike lists, sets are unordered because there is no fixed order of the elements. In other words, regardless of the order in which you put stuff into the set, you can never be sure in which order the set stores these elements. <\/p>\n<p>Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">characters = {hero, guide, enemy}\nprint(characters)\n# {'Lord V.', 'Dumbledore', 'Harry'}\n<\/pre>\n<p>You put in the hero first, but my <a href=\"https:\/\/blog.finxter.com\/python-idle-vs-pycharm\/\" data-type=\"post\" data-id=\"3345\" target=\"_blank\" rel=\"noreferrer noopener\">interpreter<\/a> prints the enemy first (the Python interpreter is on the dark side, obviously). Note that your interpreter may print yet another order of the set elements.<\/p>\n<p>(3) <strong>Unique<\/strong>: All elements in the set are unique. Each pair of values <code>(<strong>x,y<\/strong>)<\/code> in the set produces a different pair of hash values <code>(<strong>hash(x)!=hash(y)<\/strong>)<\/code>. <\/p>\n<p>Hence, every two elements <strong><code>x<\/code><\/strong> and <strong>y<\/strong> in the set are different\u2014as a result, we cannot create an army of Harry Potter clones to fight Lord V:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">clone_army = {hero, hero, hero, hero, hero, enemy}\nprint(clone_army)\n# {'Lord V.', 'Harry'}\n<\/pre>\n<p>No matter how often you put the same value into the same set, the set stores only one instance of this value. <\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" data-type=\"post\" data-id=\"1908\" target=\"_blank\" rel=\"noreferrer noopener\">A Simple Guide to Python Sets<\/a><\/p>\n<p>Note that an extension of the normal set data structure is the <em>multiset data structure<\/em> that can store multiple instances of the same value. However, it is seldom used in practice, so I don&#8217;t introduce it here.<\/p>\n<h3>Dictionary<\/h3>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"600\" height=\"400\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-101.png\" alt=\"\" class=\"wp-image-630409\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-101.png 600w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-101-300x200.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/figure>\n<\/div>\n<p>The dictionary is a useful data structure for storing (key, value)<br \/>\npairs.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">calories = {'apple' : 52, 'banana' : 89, 'choco' : 546}<\/pre>\n<p>You can read and write elements by specifying the key within brackets. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print(calories['apple'] &lt; calories['choco'])\n# True calories['cappu'] = 74 print(calories['banana'] &lt; calories['cappu'])\n# False\n<\/pre>\n<p>Use the <code><a href=\"https:\/\/blog.finxter.com\/python-dict-keys-method\/\" data-type=\"post\" data-id=\"37711\" target=\"_blank\" rel=\"noreferrer noopener\">keys()<\/a><\/code><strong> <\/strong>and <code><a href=\"https:\/\/blog.finxter.com\/python-dictionary-values-method\/\" data-type=\"post\" data-id=\"51691\" target=\"_blank\" rel=\"noreferrer noopener\">values()<\/a><\/code> functions to access all keys and values of the dictionary.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">print('apple' in calories.keys())\n# True print(52 in calories.values())\n# True\n<\/pre>\n<p>Access the <code>(key, value)<\/code><strong> <\/strong>pairs of a dictionary with the <code><a href=\"https:\/\/blog.finxter.com\/python-dict-items-method\/\" data-type=\"post\" data-id=\"37673\" target=\"_blank\" rel=\"noreferrer noopener\">items()<\/a><\/code> method. <\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">for k, v in calories.items(): print(k) if v > 500 else None\n# 'choco'\n<\/pre>\n<p>This way, it&#8217;s easy to <a href=\"https:\/\/blog.finxter.com\/iterate-over-a-dictionary-python\/\" data-type=\"post\" data-id=\"31837\" target=\"_blank\" rel=\"noreferrer noopener\">iterate over all keys and all values<\/a> in a dictionary without accessing those individually.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" data-type=\"post\" data-id=\"5232\" target=\"_blank\">A Simple Guide to Python Dictionaries<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqX0qqEVpP5s%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<h3>Tuples<\/h3>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"768\" height=\"432\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-99.png\" alt=\"\" class=\"wp-image-630315\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-99.png 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-99-300x169.png 300w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/figure>\n<p class=\"has-base-background-color has-background\"><strong>A Python tuple is an immutable, ordered, and iterable container data structure that can hold arbitrary and heterogeneous immutable data elements.<\/strong><\/p>\n<p>Here&#8217;s a basic example of tuple creation and usage:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">t = (1, 2, 'Python', tuple(), (42, 'hi')) for i in range(5): print(t[i]) '''\n1\n2\nPython\n()\n(42, 'hi') '''\n<\/pre>\n<p>The tuple data structure is a built-in data structure of the Python language with the following characteristics:<\/p>\n<ul>\n<li>Tuples are <strong>containers<\/strong>, you can store data in them. The Python documentation defines a container as an object which implements the method <code>__contains__<\/code>. In other words a container is something you can use the <em><code>in<\/code><\/em> operator on. Other examples of containers in Python are list, dict, set or frozenset. The module collection contains more container types.<\/li>\n<li>Tuples are <strong>ordered<\/strong>, each element has its position or, the other way round, the position has meaning.<\/li>\n<li>Tuples are <strong>iterable<\/strong>, so you can use them, for example, in a for loop.<\/li>\n<li>Tuples are <strong>immutable<\/strong> which means, you can\u2019t change a tuple once it was created. Once a tuple was created you can\u2019t modify it anymore. Another example of an immutable data type in Python is string. You can\u2019t modify tuples or strings in Python, instead, Python creates a new instance with the modified values. However, if a tuple contains mutable data types such as lists, the elements of those lists can change! Yet, the references in the tuple to those lists can\u2019t.<\/li>\n<li>Tuples are <strong>heterogenous<\/strong> because they can contain elements of several different data types at once. An example of a homogenous data type are strings because they can only contain characters.<\/li>\n<\/ul>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FD2i-SmUELJI%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" target=\"_blank\" rel=\"noreferrer noopener\">The Ultimate Guide to Python Tuples<\/a><\/p>\n<\/p>\n<h2 id=\"membership\">Membership<\/h2>\n<p class=\"has-base-background-color has-background\">Python\u2019s \u201c<code>in<\/code>\u201d operator is a reserved <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-cheat-sheet\/\" target=\"_blank\">keyword <\/a>to test membership of the left operand in the collection defined as the right operand. For example, the expression <code>x in my_list checks<\/code> if object <code>x<\/code> exists in the <code>my_list<\/code> collection, so that at least one element <code>y<\/code> exists in <code>my_list<\/code> for that <code>x == y<\/code> holds. You can check membership using the \u201c<code>in<\/code>\u201d operator in collections such as <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\">lists<\/a>, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/sets-in-python\/\" target=\"_blank\">sets<\/a>, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-string-methods\/\" target=\"_blank\">strings<\/a>, and <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" target=\"_blank\">tuples<\/a>.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-100.png\" alt=\"\" class=\"wp-image-630375\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-100.png 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-100-300x169.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-100-768x432.png 768w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n<p>Check with the keyword <code>in<\/code> whether the set, list, or dictionary contains an element. Note that set membership is faster than list membership.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">basket = {'apple', 'eggs', 'banana', 'orange'} print('eggs' in basket)\n# True print('mushroom' in basket)\n# False\n<\/pre>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-membership-in-operator\/\" data-type=\"post\" data-id=\"34005\" target=\"_blank\">A Simple Guide to the Membership Operator in Python<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoQkfuBAk9lo%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p>Also, check out our &#8220;negative membership&#8221; operator tutorial <a href=\"https:\/\/blog.finxter.com\/python-membership-not-in-operator\/\" data-type=\"post\" data-id=\"34063\" target=\"_blank\" rel=\"noreferrer noopener\">here<\/a>.<\/p>\n<h2 id=\"list-comprehension\">List and Set Comprehension<\/h2>\n<p>List comprehension is a popular Python feature that helps you to create lists. The simple formula is <strong><code>[ expression + context ]<\/code><\/strong>.<\/p>\n<p><strong>Expression<\/strong>: What to do with each list element?<\/p>\n<p><strong>Context<\/strong>: What list elements to select? The context consists of an arbitrary number of for and if statements.<\/p>\n<p>For example, the list comprehension statement <strong><code>[x for x in range(3)]<\/code><\/strong> creates the list<strong> <code>[0, 1, 2]<\/code><\/strong>. <\/p>\n<p>Another example is the following:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># (name, $-income)\ncustomers = [(\"John\", 240000), (\"Alice\", 120000), (\"Ann\", 1100000), (\"Zach\", 44000)] # your high-value customers earning >$1M\nwhales = [x for x,y in customers if y>1000000]\nprint(whales)\n# ['Ann']\n<\/pre>\n<p><a href=\"https:\/\/blog.finxter.com\/brackets-a-simple-introduction-to-set-comprehension-in-python\/\" data-type=\"post\" data-id=\"1153\" target=\"_blank\" rel=\"noreferrer noopener\">Set comprehension<\/a> is like list comprehension but creates a set rather than a list.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\">A Simple Guide to List Comprehension in Python<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/python-crash-course\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<h2 id=\"summary\">Summary<\/h2>\n<p>This article gave you a concise Python crash course to refresh your basic Python education. <\/p>\n<p>You studied the most important <strong>Python keywords<\/strong> and how to use them in code examples. <\/p>\n<p>As a result, you learned how to control the program execution flow using <strong>if-<g class=\"gr_ gr_9 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling\" id=\"9\" data-gr-id=\"9\">elif<\/g>-else<\/strong> statements, as well as the <strong>while <\/strong>and the <strong>for loop<\/strong>. <\/p>\n<p>Moreover, you revisited the<strong> basic data types<\/strong> in Python\u2014<strong>Boolean, integer, float, and string<\/strong>\u2014and which built-in operations and functions are commonly used in practice. <\/p>\n<p>Most code snippets in practice and non-trivial algorithms are built around more powerful <strong>container types <\/strong>such as <strong>lists, stacks, sets, and dictionaries<\/strong>. By studying the given examples, you learned how to add, remove, insert, and reorder elements. <\/p>\n<p>Finally, you learned about <strong>membership operators<\/strong> and <strong>list comprehension<\/strong>: an efficient and powerful built-in method to create lists programmatically in Python.<\/p>\n<hr class=\"wp-block-separator has-css-opacity\"\/>\n<p>I wrote this 5000<g class=\"gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace\" id=\"5\" data-gr-id=\"5\">&#8212;<\/g>word article for my best-selling book &#8220;<a rel=\"noreferrer noopener\" href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\">Python One-Liners<\/a>&#8221; with the San Francisco-based publisher NoStarch. <\/p>\n<h2>Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-1024x944.jpg\" alt=\"Python One-Liners\" class=\"wp-image-10007\" width=\"512\" height=\"472\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<\/div>\n<p><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Python One-Liners<\/em> <\/a>will teach you how to read and write &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. <\/em><\/strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. <\/p>\n<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts <\/em><\/strong>and<strong><em> boost your coding and analytical skills<\/em><\/strong>. You&#8217;ll learn about advanced Python features such as <em><strong>list comprehension<\/strong><\/em>, <strong><em>slicing<\/em><\/strong>, <strong><em>lambda functions<\/em><\/strong>, <strong><em>regular expressions<\/em><\/strong>, <strong><em>map <\/em><\/strong>and <strong><em>reduce <\/em><\/strong>functions, and <strong><em>slice assignments<\/em><\/strong>. <\/p>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<li>Use <strong>NumPy basics<\/strong> such as <em>array<\/em>, <em>shape<\/em>, <em>axis<\/em>, <em>type<\/em>, <em>broadcasting<\/em>, <em>advanced indexing<\/em>, <em>slicing<\/em>, <em>sorting<\/em>, <em>searching<\/em>, <em>aggregating<\/em>, and <em>statistics<\/em><\/li>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<li>Create more <strong>advanced regular expressions<\/strong> using <em>grouping <\/em>and <em>named groups<\/em>, <em>negative lookaheads<\/em>, <em>escaped characters<\/em>, <em>whitespaces, character sets<\/em> (and <em>negative characters sets<\/em>), and <em>greedy\/nongreedy operators<\/em><\/li>\n<li>Understand a wide range of <strong>computer science topics<\/strong>, including <em>anagrams<\/em>, <em>palindromes<\/em>, <em>supersets<\/em>, <em>permutations<\/em>, <em>factorials<\/em>, <em>prime numbers<\/em>, <em>Fibonacci <\/em>numbers, <em>obfuscation<\/em>, <em>searching<\/em>, and <em>algorithmic sorting<\/em><\/li>\n<\/ul>\n<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined<\/em><\/strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<p><strong><a href=\"https:\/\/amzn.to\/2WAYeJE\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/amzn.to\/2WAYeJE\"><em>Get your Python One-Liners on Amazon!!<\/em><\/a><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (5 votes) (Reading time: 19 minutes) The purpose of this article is to help you refresh your knowledge of all the basic Python keywords, data structures, and fundamentals. I wrote it for the intermediate Python programmer who wants to reach the next level of programming expertise. The way of achieving an expert level [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-127703","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127703","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127703"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127703\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127703"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127703"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127703"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}