avatarHaider Imtiaz

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

12687

Abstract

Tom"</span>]</pre></div><div id="bd51"><pre><span class="hljs-variable">mydict</span> = <span class="hljs-function"><span class="hljs-title">dict</span>(<span class="hljs-title">enumerate</span>(<span class="hljs-variable">mydict</span>))</span></pre></div><div id="6d98"><pre><span class="hljs-built_in">print</span>(mydict) # {0: <span class="hljs-string">'John'</span>, 1: <span class="hljs-string">'Peter'</span>, 2: <span class="hljs-string">'Mathew'</span>, 3: <span class="hljs-string">'Tom'</span>}</pre></div><h1 id="0f6c">10# — Multi-Variable in One line</h1><p id="62b0">Python allows multiple variable assignments in one line. Below example code will show you how to do that.</p><div id="9270"><pre>#Multi Line <span class="hljs-built_in">Variable</span></pre></div><div id="9571"><pre><span class="hljs-comment">#Normal Way</span> <span class="hljs-attribute">x</span> = <span class="hljs-number">5</span> <span class="hljs-attribute">y</span> = <span class="hljs-number">7</span> <span class="hljs-attribute">z</span> = <span class="hljs-number">10</span> <span class="hljs-attribute">print</span>(x , y, z) # <span class="hljs-number">5</span> <span class="hljs-number">7</span> <span class="hljs-number">10</span></pre></div><div id="4c30"><pre><span class="hljs-comment">#One Line way</span> <span class="hljs-attribute">a</span>, b, c = <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">10</span> <span class="hljs-attribute">print</span>(a, b, c) # <span class="hljs-number">5</span> <span class="hljs-number">7</span> <span class="hljs-number">10</span></pre></div><h1 id="d110">11# — Swap in One Line</h1><p id="0c5c">Swapping is an interesting task in Programming and always required a third variable name temp to save swap values. This One line snippet will show you how to swap values in one line without any temp variable.</p><div id="d2d1"><pre>#Swap <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="fee4"><pre><span class="hljs-meta">#Normal way</span></pre></div><div id="b9b9"><pre>v1 = 100 v2 = 200 temp = v1 v1 = v2 v2 = temp print(v1, v2) <span class="hljs-comment"># 200 100</span></pre></div><div id="1229"><pre><span class="hljs-comment"># One Line Swapping</span> v1, v2 = v2, v1 print(v1, v2) <span class="hljs-comment"># 200 100</span></pre></div><h1 id="51ad">12# — Sort in One Line</h1><p id="bf7a">Sorting is a general problem in Programming and Python had many built-in methods to solve this sorting problem. Below is the code example that will show how to sort in one line.</p><div id="6f12"><pre># <span class="hljs-keyword">Sort</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="c95d"><pre>mylist = [<span class="hljs-number">32</span>, <span class="hljs-number">22</span>, <span class="hljs-number">11</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>]

<span class="hljs-keyword">method</span> 1</pre></div><div id="ab7c"><pre>mylist<span class="hljs-selector-class">.sort</span>()

<span class="hljs-built_in">print</span>(mylist) # # <span class="hljs-selector-attr">[4, 6, 8, 11, 12, 22, 32]</span></pre></div><div id="c0f6"><pre><span class="hljs-built_in">print</span>(<span class="hljs-built_in">sorted</span>(mylist)) <span class="hljs-comment"># [4, 6, 8, 11, 12, 22, 32]</span></pre></div><h1 id="3734">13# — Read File in One Line</h1><p id="ab86">It is possible to read the file in one line correctly without using the statement or normal reading method.</p><div id="d352"><pre>#<span class="hljs-keyword">Read</span> <span class="hljs-keyword">File</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="4ddd"><pre><span class="hljs-meta">#Normal Way</span></pre></div><div id="a3b6"><pre><span class="hljs-title">with</span> open(<span class="hljs-string">"data.txt"</span>, <span class="hljs-string">"r"</span>) <span class="hljs-keyword">as</span> file: <span class="hljs-class"><span class="hljs-keyword">data</span> = file.readline()</span> print(<span class="hljs-class"><span class="hljs-keyword">data</span>) # <span class="hljs-type">Hello</span> world</span></pre></div><div id="8f3f"><pre>#<span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span> Way</pre></div><div id="e9b0"><pre>data = [<span class="hljs-type">line</span>.strip() <span class="hljs-keyword">for</span> <span class="hljs-type">line</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">open</span>("data.txt","r")] print(data) # [<span class="hljs-string">'hello world'</span>, <span class="hljs-string">'Hello Python'</span>]</pre></div><h1 id="8c09">14# — Class in One Line</h1><p id="2df3">Class is always multi-line work. But in Python, there are some ways in which you can use class-like features in One line of codes.</p><div id="4a95"><pre># <span class="hljs-keyword">Class</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="dec8"><pre><span class="hljs-comment">#Normal way </span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Emp</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, name, age</span>): <span class="hljs-variable language_">self</span>.name = name <span class="hljs-variable language_">self</span>.age = age</pre></div><div id="0875"><pre><span class="hljs-attribute">emp1</span> = Emp(<span class="hljs-string">"Haider"</span>, <span class="hljs-number">22</span>) <span class="hljs-attribute">print</span>(emp1.name, emp1.age) # Haider <span class="hljs-number">22</span></pre></div><div id="3c58"><pre>#<span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span> Way</pre></div><div id="fc25"><pre>#<span class="hljs-keyword">method</span> 1 <span class="hljs-title function_">Lambda</span> <span class="hljs-title function_">with</span> <span class="hljs-title function_">Dynamic</span> <span class="hljs-title function_">Artibutes</span></pre></div><div id="30da"><pre><span class="hljs-attr">Emp</span> = lambda: None<span class="hljs-comment">; Emp.name = "Haider"; Emp.age = 22</span></pre></div><div id="f339"><pre><span class="hljs-keyword">print</span>(Emp.name, Emp.age) <span class="hljs-meta"># Haider 22</span></pre></div><div id="e5ee"><pre>#<span class="hljs-keyword">method</span> 2 <span class="hljs-title function_">from</span> <span class="hljs-title function_">collections</span> <span class="hljs-title function_">import</span> <span class="hljs-title function_">namedtuple</span></pre></div><div id="fc14"><pre>Emp = namedtuple('Emp', [<span class="hljs-string">"name"</span>, <span class="hljs-string">"age"</span>]) (<span class="hljs-string">"Haider"</span>, <span class="hljs-number">22</span>) print(<span class="hljs-name">Emp</span>.name, Emp.age) # Haider <span class="hljs-number">22</span></pre></div><h1 id="80de">15# — Semi-Colon in One Line</h1><p id="4ba6">The semi-Colon in one line snippet will show you how to write multiple lines of code in one using semi-colons.</p><div id="0836"><pre><span class="hljs-comment"># Semi colon in One Line</span></pre></div><div id="c27a"><pre><span class="hljs-comment">#example 1</span> <span class="hljs-keyword">a</span> = <span class="hljs-string">"Python"</span>; b = <span class="hljs-string">"Programming"</span>; c = <span class="hljs-string">"Language"</span>; print(<span class="hljs-keyword">a</span>, b, c)</pre></div><div id="de2b"><pre><span class="hljs-meta">#output:</span> <span class="hljs-meta"># Python Programming Language</span></pre></div><h1 id="fb96">16# — Print in One Line</h1><p id="b7b5">This is not much important Snippet but it is useful sometimes when you don’t need to use a loop to do a task.</p><div id="7181"><pre># <span class="hljs-keyword">Print</span> <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="d278"><pre><span class="hljs-meta">#Normal Way</span></pre></div><div id="0cbb"><pre><span class="hljs-attribute">for</span> x in range(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>): <span class="hljs-attribute">print</span>(x) # <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">4</span></pre></div><div id="a4bd"><pre>#<span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span> Way</pre></div><div id="aac0"><pre><span class="hljs-attribute">print</span>(*range(<span class="hljs-number">1</span>, <span class="hljs-number">5</span>)) # <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">4</span> <span class="hljs-attribute">print</span>(range(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>)) # <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span> <span class="hljs-number">4</span> <span class="hljs-number">5</span></pre></div><h1 id="142a">17# — Map Function in One Line</h1><p id="6f05">The Map function is a higher-order function that applies. That applies a function to every element. Below is the Example that how we can use the map function in one line of Code.</p><div id="5e89"><pre>#Map <span class="hljs-keyword">in</span> <span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span></pre></div><div id="ccd1"><pre><span class="hljs-selector-tag">print</span>(<span class="hljs-built_in">list</span>(<span class="hljs-built_in">map</span>(lambda <span class="hljs-attribute">a</span>: a + <span class="hljs-number">2</span>, [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>])))</pre></div><div id="a332"><pre><span class="hljs-meta">#output</span> <span class="hljs-meta"># [7, 8, 9, 10, 11, 12]</span></pre></div><h1 id="cdd8">18# — Delete Mul Element in List One Line</h1><p id="372f">You can now delete multiple elements in the List in one line of code using the <b>del method </b>with little modification<b>.</b></p><div id="083f"><pre><span class="hljs-type">#</span> <span class="hljs-built_in">Delete</span> <span class="hljs-variable">Mul</span> <span class="hljs-built_in">Element</span> <span class="hljs-variable">in</span> <span class="hljs-variable">One</span> <span class="hljs-built_in">Line</span></pre></div><div id="0aa5"><pre><span class="hljs-attr">mylist</span> = [<span class="hljs-number">100</span>, <span class="hljs-number">200</span>, <span class="hljs-number">300</span>, <span class="hljs-number">400</span>, <span class="hljs-number">500</span>]</pre></div><div id="98c4"><pre><span class="hljs-attribute">del</span> mylist[<span class="hljs-number">1</span>::<span class="hljs-number">2</span>]</pre></div><div id="8557"><pre><span class="hljs-built_in">print</span>(mylist) # <span class="hljs-selector-attr">[100, 300, 500]</span></pre></div><h1 id="cfce">19# — Print Pattern in One Line</h1><p id="946f">Now you no longer need to use Loop for printing the same pattern. You can use Print statement and asterisk () to do the same thing in one line of code.</p><div id="b38c"><pre><span class="hljs-type">#</span> <span class="hljs-built_in">Print</span> <span class="hljs-built_in">Pattern</span> <span class="hljs-variable">in</span> <span class="hljs-variable">One</span> <span class="hljs-built_in">Line</span></pre></div><div id="e6af"><pre># <span class="hljs-attribute">Normal</span> Way for x in <span class="hljs-built_in">range</span>(<span class="hljs-number">3</span>): <span class="hljs-built_in">print</span>(<span class="hljs-string">'😀'</span>)</pre></div><div id="d2c6"><pre><span class="hljs-meta"># output </span> <span class="hljs-meta"># 😀 😀 😀</span></pre></div><div id="83af"><pre>#<span class="hljs-keyword">One</span> <span class="hljs-keyword">Line</span> way</pre></div><div id="c06f"><pre><span class="hljs-keyword">print</span>(<span class="hljs-string">'😀'</span> * <span class="hljs-number">3</span>) <span class="hljs-meta"># 😀

Options

😀 😀</span> <span class="hljs-keyword">print</span>(<span class="hljs-string">'😀'</span> * <span class="hljs-number">2</span>) <span class="hljs-meta"># 😀 😀 </span> <span class="hljs-keyword">print</span>(<span class="hljs-string">'😀'</span> * <span class="hljs-number">1</span>) <span class="hljs-meta"># 😀</span></pre></div><h1 id="961d">20# — Find Prime Number in One Line</h1><p id="212c">This snippet will show you how to write a one-liner code to find the Prime number within the range.</p><div id="e05b"><pre><span class="hljs-type">#</span> <span class="hljs-built_in">Find</span> <span class="hljs-built_in">Prime</span> <span class="hljs-built_in">Number</span></pre></div><div id="7186"><pre><span class="hljs-selector-tag">print</span>(<span class="hljs-built_in">list</span>(<span class="hljs-built_in">filter</span>(lambda <span class="hljs-attribute">a</span>: <span class="hljs-built_in">all</span>(a % b != <span class="hljs-number">0</span> for b in <span class="hljs-built_in">range</span>(<span class="hljs-number">2</span>, a)), <span class="hljs-built_in">range</span>(<span class="hljs-number">2</span>,<span class="hljs-number">20</span>))))</pre></div><div id="94fc"><pre><span class="hljs-meta">#Output</span> <span class="hljs-meta"># [2, 3, 5, 7, 11, 13, 17, 19]</span></pre></div><h1 id="36e2">Final Thoughts</h1><p id="89cc">I had shared the useful and interesting one-liner Python snippets with you. I hope you enjoy and learn something. Share it with your friends and other Python Programmers you know. Feel free to leave a response. <b>Happy Codding!</b></p><h1 id="c5be">Learn More</h1><p id="32e8">Are you a Python Fan and want some more Python shots, Check out my below Python articles? 😀.</p><div id="cefa" class="link-block"> <a href="https://python.plainenglish.io/15-useful-snippets-for-your-daily-life-python-problems-846aae52772f"> <div> <div> <h2>15 Useful Snippets for your Daily life Python Problems</h2> <div><h3>Digitizing, Generic Swapping, Hex_To_RGB, Print Same line Sort Dictionary, and many more useful snippets</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*BFjwjy1oHlV9eL4Ii6kecg.jpeg)"></div> </div> </div> </a> </div><div id="ddb1" class="link-block"> <a href="https://python.plainenglish.io/22-useful-snippets-to-code-like-a-pro-in-python-1d0dcaacac69"> <div> <div> <h2>22 Useful Snippets to Code like a Pro in Python</h2> <div><h3>Get vowels, finding anagrams, sorting dictionary, n times string, byte sizing, filtering, etc. You will learn much more…</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*8lhZBBja11Pf4_K1IYCj-Q.png)"></div> </div> </div> </a> </div><div id="dcf3" class="link-block"> <a href="https://python.plainenglish.io/top-python-tricks-that-will-boost-your-skills-c55e8268ca5f"> <div> <div> <h2>Top Python Tricks That Will Boost Your Skills</h2> <div><h3>Most used tricks that will boost your Python programming skills.</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*3Fr1uaEJfdad-mVLbPMaIg.png)"></div> </div> </div> </a> </div><div id="d999" class="link-block"> <a href="https://python.plainenglish.io/hidden-features-of-python-that-you-have-probably-never-heard-of-47af1e8abee2"> <div> <div> <h2>Python Hidden Features That You Probably Never Heard Of</h2> <div><h3>Lesser-known Python Features, Tips, and Tricks</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*NKDm9kgiBXLl2SNElFmRBg.jpeg)"></div> </div> </div> </a> </div><div id="f160" class="link-block"> <a href="https://python.plainenglish.io/22-helpful-python-tips-and-tricks-for-beginners-43c4a8f56a1c"> <div> <div> <h2>Useful Tips and Tricks for Python Programmers</h2> <div><h3>Super Awesome Tips and Tricks for better and Pro coding in Python you should know as a Programmer.</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Ro7Fogu5keiL5jA4.png)"></div> </div> </div> </a> </div><div id="5b10" class="link-block"> <a href="https://python.plainenglish.io/17-python-tips-and-tricks-to-boost-your-coding-skills-5e14054001b2"> <div> <div> <h2>17 Python Tips and Tricks to Boost your Coding Skills</h2> <div><h3>Make your life easier with these Top Python Tips and Tricks</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*Q5zOL3rCGnljaBnrwrpr0w.png)"></div> </div> </div> </a> </div><div id="00df" class="link-block"> <a href="https://python.plainenglish.io/from-zero-to-hero-in-python-in-just-10-minutes-83064ffd5aee"> <div> <div> <h2>From Zero to Hero in Python in Just 10 minutes</h2> <div><h3>Everything you need to learn to go from zero to hero in Python.</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*uogTxM0a-lVa__VkjFBjew.jpeg)"></div> </div> </div> </a> </div><div id="e621" class="link-block"> <a href="https://python.plainenglish.io/25-programming-jokes-to-make-you-lol-8bf793eb2a52"> <div> <div> <h2>25 Programming Jokes To Make You LOL</h2> <div><h3>Some funny programming jokes to make you smile and laugh</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*x3fGnT5-vln_l_OK)"></div> </div> </div> </a> </div><div id="036a" class="link-block"> <a href="https://python.plainenglish.io/top-python-shortcuts-c0345d5a48ec"> <div> <div> <h2>Top Python Shortcuts</h2> <div><h3>15 Python Tips and Tricks that make your life easier</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*-IYcE6-YJTX_brw67C6aRA.jpeg)"></div> </div> </div> </a> </div><div id="1d78" class="link-block"> <a href="https://python.plainenglish.io/12-python-interesting-facts-that-you-might-not-know-72dcb90b8ea"> <div> <div> <h2>12 Python Interesting Facts That You Might Not Know</h2> <div><h3>12 Facts I Bet You Didn’t Know About Python</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*X_xqpHrzODjl8K4YMOGAuQ.jpeg)"></div> </div> </div> </a> </div><div id="a0f1" class="link-block"> <a href="https://python.plainenglish.io/python-snippets-you-should-learn-today-e796456bd6db"> <div> <div> <h2>Python Snippets You Should Learn Today</h2> <div><h3>Top Python snippets that save your valuable time and make your life easier.</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*fqvnEW_Ixk3vfLQu44xjRA.jpeg)"></div> </div> </div> </a> </div><div id="8b52" class="link-block"> <a href="https://python.plainenglish.io/best-ways-to-earn-1000-in-a-month-with-programming-fbb70cf553da"> <div> <div> <h2>7 Ways to Earn 1000 in a Month with Programming</h2> <div><h3>In this article, we will see the best ways to earn 1000 online in a month if you are a programmer. Well, you had…</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*4rfHyoDrhAlptiYq)"></div> </div> </div> </a> </div><div id="0864" class="link-block"> <a href="https://python.plainenglish.io/build-your-first-simple-django-web-app-with-python-9a4452157089"> <div> <div> <h2>Build your first Simple Django Web App With Python</h2> <div><h3>Django is a Python open-source web development framework for rapid web app design. Today, we’ll introduce Django and…</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*khNdKoKBXaIczaax)"></div> </div> </div> </a> </div><div id="e51f" class="link-block"> <a href="https://python.plainenglish.io/step-by-step-guide-to-converting-your-py-file-to-an-exe-file-f86eb0b5f253"> <div> <div> <h2>Step by Step Guide to Converting Your .py File to an .exe File</h2> <div><h3>Looking for a guide for converting your python file to an executable ( .exe ) file. In this article, we will learn…</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*GvPP9cBdy2M7VqYgge9SQQ.png)"></div> </div> </div> </a> </div><div id="d317" class="link-block"> <a href="https://python.plainenglish.io/how-to-read-and-write-pdf-files-using-python-7b930977fe58"> <div> <div> <h2>How to Read and Write PDF files using Python</h2> <div><h3>Extract Text, Tables, Images from PDF Files, and much more to learn in this article</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*x56MaZgeveeGzOZSGoVK6Q.jpeg)"></div> </div> </div> </a> </div><div id="29ad" class="link-block"> <a href="https://python.plainenglish.io/how-to-read-and-write-to-json-file-in-python-ef35460aaeb5"> <div> <div> <h2>How to Read and Write to JSON File in Python</h2> <div><h3>JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transferring data, even it is…</h3></div> <div><p>python.plainenglish.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*7egri62bf4B8ebEmK17RfA.jpeg)"></div> </div> </div> </a> </div><p id="f6fd"><i>More content at <a href="http://plainenglish.io/"><b>plainenglish.io</b></a></i></p></article></body>

20 Extremely Useful Python One-Liners You Must Know

Useful Python one-liner Snippets to solve any coding problem in just one line

Photo by Andrea Piacquadio from Pexels

In this blog, I will share 20 Python one-liners that you can easily learn in 30 seconds or less time on each. This one-liner code will save your time and will make your code look cleaner and easy to read.

1# — For Loop in One Line

For loop is a multi-line statement, But in Python, we can write for loop in one line using the List Comprehension method. Let take an example of filtering values that are lesser than 250. Check out the Below code example.

#For loop in One line
mylist = [100, 200, 300, 400, 500]
#Orignal way
result = []
for x in mylist:
    if x > 250:
        result.append(x)
print(result) # [300, 400, 500]
#One Line Way
result = [x for x in mylist if x > 250]
print(result) # [300, 400, 500]

2# — While Loop in One Line

This One-Liner snippet will show you how to use the While loop code in One Line, I had shown two methods of doing this.

#method 1 Single Statement
while True: print(1)  # infinite 1
#method 2 Multiple Statement
x = 0
while x < 5: print(x); x= x + 1  # 0 1 2 3 4 5

3# — IF Else Statement in One Line

Well, to write the IF Else statement in One Line we will use the ternary operator. Syntax of Ternary is “[on true] if [expression] else [on false]”.

I had shown 3 examples in the below example code to make your understanding clear that how to use the ternary operator for one line if-else statement. To use the Elif statement we had to use multiple Ternary operators.

#if Else in One Line
#Example 1 if else
print("Yes") if 8 > 9 else print("No")  # No
#Example 2 if elif else
E = 2
print("High") if E == 5 else print("Meidum") if E == 2 else print("Low") # Medium
 
#Example 3 only if
if 3 > 2: print("Exactly") # Exactly

4# — Merge Dictionary in One Line

This One line Snippet will show you how to merge two dictionaries into one with One Line of code. Below I have shown two methods to merge dictionaries.

# Merge Dictionary in One Line
d1 = { 'A': 1, 'B': 2 }
d2 = { 'C': 3, 'D': 4 }
#method 1
d1.update(d2)
print(d1) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}
#method 2
d3 = {**d1, **d2}
print(d3) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}

5# — Function in One Line

We had two methods to write Functions in one line, In the first method, we will use the same function definition with the ternary operator or one-line loop methods.

The second method is to define functions with lambda. Check out the example code below for more clear understanding.

#Function in One Line
#method 1
def fun(x): return True if x % 2 == 0 else False
print(fun(2)) # False
#method 2
fun = lambda x : x % 2 == 0 
print(fun(2)) # True
print(fun(3)) # False

6# — Recursion in One Line

This One-Liner Snippet will show how to use Recursion in one line. we will use one line function definition with one line if-else statement. Below is an example of finding the Fibonacci numbers.

# Recursion in One Line
#Fibonaci example with one line Recursion
def Fib(x): return 1 if x in {0, 1} else Fib(x-1) + Fib(x-2)
print(Fib(5)) # 8
print(Fib(15)) # 987

7# — Array Filtering in One Line

Python lists can be filtered in one line of code by using the list comprehension method. Let take the example of filtering a list with even numbers.

# Array Filtering in One Line
mylist = [2, 3, 5, 8, 9, 12, 13, 15]
#Normal Way
result = []
for x in mylist:
    if x % 2 == 0:
        result.append(x)
print(result) # [2, 8, 12]
#One Line Way
result = [x for x in mylist if x % 2 == 0]
print(result) # [2, 8, 12]

8# — Exception Handling One Line

We used Exception handling to deal with runtimes errors in Python. Do you know we can write this Try Except statement in One-Line? By using the exec() statement we can do this.

# Exception Handling in One Line
#Original Way
try:
    print(x)
except:
    print("Error")
#One Line Way
exec('try:print(x) \nexcept:print("Error")') # Error

9# — List to Dictionary in One Line

We can convert List to Dictionary in One Line using Python enumerate() function. Pass the list in enumerate() and use dict() to convert the final output in dictionary format.

# Dictionary in One line
mydict = ["John", "Peter", "Mathew", "Tom"]
mydict = dict(enumerate(mydict))
print(mydict) # {0: 'John', 1: 'Peter', 2: 'Mathew', 3: 'Tom'}

10# — Multi-Variable in One line

Python allows multiple variable assignments in one line. Below example code will show you how to do that.

#Multi Line Variable
#Normal Way
x = 5
y = 7 
z = 10
print(x , y, z) # 5 7 10
#One Line way
a, b, c = 5, 7, 10
print(a, b, c) # 5 7 10

11# — Swap in One Line

Swapping is an interesting task in Programming and always required a third variable name temp to save swap values. This One line snippet will show you how to swap values in one line without any temp variable.

#Swap in One Line
#Normal way
v1 = 100
v2 = 200
temp = v1
v1 = v2 
v2 = temp
print(v1, v2) # 200 100
# One Line Swapping
v1, v2 = v2, v1
print(v1, v2) # 200 100

12# — Sort in One Line

Sorting is a general problem in Programming and Python had many built-in methods to solve this sorting problem. Below is the code example that will show how to sort in one line.

# Sort in One Line
mylist = [32, 22, 11, 4, 6, 8, 12]
# method 1
mylist.sort()
print(mylist) # # [4, 6, 8, 11, 12, 22, 32]
print(sorted(mylist)) # [4, 6, 8, 11, 12, 22, 32]

13# — Read File in One Line

It is possible to read the file in one line correctly without using the statement or normal reading method.

#Read File in One Line
#Normal Way
with open("data.txt", "r") as file:
    data = file.readline()
    print(data) # Hello world
#One Line Way
data = [line.strip() for line in open("data.txt","r")]
print(data) # ['hello world', 'Hello Python']

14# — Class in One Line

Class is always multi-line work. But in Python, there are some ways in which you can use class-like features in One line of codes.

# Class in One Line
#Normal way 
class Emp:
    def __init__(self, name, age):
        self.name = name
        self.age = age
emp1 = Emp("Haider", 22)
print(emp1.name, emp1.age) # Haider 22
#One Line Way
#method 1 Lambda with Dynamic Artibutes
Emp = lambda: None; Emp.name = "Haider"; Emp.age = 22
print(Emp.name, Emp.age) # Haider 22
#method 2
from collections import namedtuple
Emp = namedtuple('Emp', ["name", "age"]) ("Haider", 22)
print(Emp.name, Emp.age) # Haider 22

15# — Semi-Colon in One Line

The semi-Colon in one line snippet will show you how to write multiple lines of code in one using semi-colons.

# Semi colon in One Line
#example 1
a = "Python"; b = "Programming"; c = "Language"; print(a, b, c)
#output:
# Python Programming Language

16# — Print in One Line

This is not much important Snippet but it is useful sometimes when you don’t need to use a loop to do a task.

# Print in One Line
#Normal Way
for x in range(1, 5):
    print(x) # 1 2 3 4
#One Line Way
print(*range(1, 5)) # 1 2 3 4
print(*range(1, 6)) # 1 2 3 4 5

17# — Map Function in One Line

The Map function is a higher-order function that applies. That applies a function to every element. Below is the Example that how we can use the map function in one line of Code.

#Map in One Line
print(list(map(lambda a: a + 2, [5, 6, 7, 8, 9, 10])))
#output
# [7, 8, 9, 10, 11, 12]

18# — Delete Mul Element in List One Line

You can now delete multiple elements in the List in one line of code using the del method with little modification.

# Delete Mul Element in One Line
mylist = [100, 200, 300, 400, 500]
del mylist[1::2]
print(mylist) # [100, 300, 500]

19# — Print Pattern in One Line

Now you no longer need to use Loop for printing the same pattern. You can use Print statement and asterisk (*) to do the same thing in one line of code.

# Print Pattern in One Line
# Normal Way 
for x in range(3):
    print('😀')
# output 
# 😀 😀 😀
#One Line way
print('😀' * 3) # 😀 😀 😀
print('😀' * 2) # 😀 😀 
print('😀' * 1) # 😀

20# — Find Prime Number in One Line

This snippet will show you how to write a one-liner code to find the Prime number within the range.

# Find Prime Number
print(list(filter(lambda a: all(a % b != 0 for b in range(2, a)), range(2,20))))
#Output
# [2, 3, 5, 7, 11, 13, 17, 19]

Final Thoughts

I had shared the useful and interesting one-liner Python snippets with you. I hope you enjoy and learn something. Share it with your friends and other Python Programmers you know. Feel free to leave a response. Happy Codding!

Learn More

Are you a Python Fan and want some more Python shots, Check out my below Python articles? 😀.

More content at plainenglish.io

Python
Python3
Programming
Coding
Software Development
Recommended from ReadMedium