Sick Gaming
[Tut] Python One Line Array - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: Python (https://www.sickgaming.net/forum-83.html)
+--- Thread: [Tut] Python One Line Array (/thread-96935.html)



[Tut] Python One Line Array - xSicKxBot - 08-28-2020

Python One Line Array

<div><p>This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you’ll become a better coder. So, let’s roll up your sleeves and get started! <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Python One Line Print Array</h2>
<p>If you just want to know the best way to print an array (list) in Python, here’s the short answer:</p>
<ul>
<li>Pass a list as an input to the <code><a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" title="Python Print Function [And Its SECRET Separator &amp; End Arguments]">print()</a></code> function in Python. </li>
<li>Use the <a rel="noreferrer noopener" href="https://blog.finxter.com/what-is-asterisk-in-python/" target="_blank">asterisk operator </a><code>*</code> in front of the list to “unpack” the list into the print function. </li>
<li>Use the <code>sep</code> argument to define how to separate two list elements visually. </li>
</ul>
<p>Here’s the code:</p>
<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=""># Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5</pre>
<p>Try It Yourself in Our Interactive Code Shell:</p>
<p> <iframe src="https://repl.it/@finxter/pythonlistprint3?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="700px" frameborder="no"></iframe> </p>
<p>This is the best and most Pythonic way to print a Python array list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—read the following tutorial!</p>
<p><strong>Related Article</strong>:<a href="https://blog.finxter.com/print-python-list/" target="_blank" rel="noreferrer noopener" title="Print a Python List Beautifully [Click &amp; Run Code]"> Print a Python List Beautifully [Click &amp; Run Code]</a></p>
<h2>Python If Else One Line Array</h2>
<p>The most basic <a href="https://blog.finxter.com/python-one-line-ternary/" target="_blank" rel="noreferrer noopener" title="Python One Line Ternary">ternary operator</a> <code>x if c else y</code> returns expression <code>x</code> if the Boolean expression <code>c</code> evaluates to <code>True</code>. Otherwise, if the expression <code>c</code> evaluates to <code>False</code>, the ternary operator returns the alternative expression <code>y</code>.</p>
<p>Here’s a minimal example:</p>
<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="">var = 21 if 3&lt;2 else 42
# var == 42</pre>
<p>While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-rich is-provider-embed-handler wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="If-Then-Else in One Line Python" width="1400" height="788" src="https://www.youtube.com/embed/ZGUAaQiO06Y?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</p></div>
</figure>
<p><strong>Related Article</strong>: <a href="https://blog.finxter.com/if-then-else-in-one-line-python/" target="_blank" rel="noreferrer noopener" title="If-Then-Else in One Line Python [Video + Interactive Code Shell]">If-Then-Else in One Line Python [Video + Interactive Code Shell]</a></p>
<h2>Python One Line For Loop Array</h2>
<p><strong>How to Write a For Loop in a Single Line of Python Code?</strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python One Line For Loop [A Simple Tutorial]" width="1400" height="788" src="https://www.youtube.com/embed/M6XNZ40lRFQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>There are two ways of writing a <a href="https://blog.finxter.com/python-one-line-for-loop-with-if/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop With If">one-liner for loop</a>:</p>
<ul>
<li><strong>Method 1</strong>: If the <a href="https://blog.finxter.com/python-loops/" target="_blank" rel="noreferrer noopener" title="Python Loops">loop </a>body consists of one statement, simply write this statement into the same line: <code>for i in range(10): print(i)</code>. This prints the first 10 numbers to the shell (from 0 to 9). </li>
<li><strong>Method 2: </strong>If the purpose of the loop is to create a list, use <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">list comprehension</a> instead: <code>squares = [i**2 for i in range(10)]</code>. The code squares the first ten numbers and stores them in the array list <code>squares</code>. </li>
</ul>
<p> <iframe src="https://trinket.io/embed/python/27248749cf" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<p>Let’s have a look at both variants in more detail in the following article:</p>
<p><strong>Related article</strong>: <a href="https://blog.finxter.com/python-one-line-for-loop-a-simple-tutorial/" target="_blank" rel="noreferrer noopener" title="Python One Line For Loop [A Simple Tutorial]">Python One Line For Loop [A Simple Tutorial]</a></p>
<h2>Python Iterate Array One Line</h2>
<p><strong><em>How to iterate over an array in a single line of code? </em></strong></p>
<p>Say, you’ve given an array (list) <code>lst</code> and you want to iterate over all values and do something with them. You can accomplish this using <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">list comprehension</a>:</p>
<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="">lst = [1, 2, 3]
squares = [i**2 for i in lst]
print(squares)
# [1, 4, 9]</pre>
<p>You iterate over all values in the array <code>lst</code> and calculate their square numbers. The result is stored in a new array list <code>squares</code>. </p>
<p>You can even print all the squared array values in a single line by creating a dummy array of None values using the print() function in the expression part of the list comprehension statement:</p>
<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="">[print(i**2) for i in lst] '''
1
4
9 '''</pre>
<p><strong>Related article</strong>: <a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide">List Comprehension Full Introduction</a></p>
<h2>Python Fill Array One Line</h2>
<p><strong><em>Do you want to fill or initialize an array with n values using only a single line of Python code?</em></strong> </p>
<p>To fill an array with an integer value, use the list multiplication feature:</p>
<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="">array = [0] * 10
print(array)
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]</pre>
<p>This creates an array of ten elements filled with the value 0. You can also fill the array with other elements by replacing the 0 with the desired element—for example, <code>[None] * 10</code> creates a list of ten <code>None</code> elements. </p>
<h2>Python Initialize Array One Line</h2>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Create a Python List?" width="1400" height="788" src="https://www.youtube.com/embed/qXOFngx0bQU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>There are many ways of creating an array (list) in Python. Let’s get a quick overview in the following table:</p>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th>Code</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>[]</code></td>
<td><strong>Square bracket</strong>: Initializes an empty list with zero elements. You can add elements later.</td>
</tr>
<tr>
<td><code>[x1, x2, x3, … ]</code></td>
<td><strong>List display:</strong> Initializes an empty list with elements <code>x1</code>, <code>x2</code>, <code>x3</code>, … For example, <code>[1, 2, 3]</code> creates a list with three integers 1, 2, and 3.</td>
</tr>
<tr>
<td><code>[expr1, expr2, ... ]</code></td>
<td><strong>List display with expressions</strong>: Initializes a list with the result of the expressions <code>expr1</code>, <code>expr2</code>, … For example, <code>[1+1, 2-1]</code> creates the list <code>[2, 1]</code>. </td>
</tr>
<tr>
<td><code>[expr for var in iter]</code></td>
<td><strong>List comprehension</strong>: applies the expression <code>expr</code> to each element in an iterable.</td>
</tr>
<tr>
<td><code>list(iterable)</code></td>
<td><strong>List constructor</strong> that takes an iterable as input and returns a new list.</td>
</tr>
<tr>
<td><code>[x1, x2, ...] * n</code></td>
<td><strong>List multiplication</strong> creates a list of n concatenations of the list object. For example <code>[1, 2] * 2 == [1, 2, 1, 2]</code>.</td>
</tr>
</tbody>
</table>
</figure>
<p>You can play with some examples in our interactive Python shell:</p>
<p> <iframe src="https://trinket.io/embed/python/c1e9402361" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="500" frameborder="0"></iframe> </p>
<p><em><strong>Exercise</strong>: Use <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener" title="List Comprehension in Python — A Helpful Illustrated Guide">list comprehension</a> to create a list of square numbers.</em></p>
<p>Let’s dive into some more specific ways to create various forms of lists in <a href="https://blog.finxter.com/python-crash-course/" title="Python Programming Tutorial [+Cheat Sheets]" target="_blank" rel="noreferrer noopener">Python</a>. </p>
<p><strong>Related Article</strong>: <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">How to Create a Python List?</a></p>
<h2>Python Filter Array One Line</h2>
<p><strong><em>How can you filter an array in Python using an arbitrary condition?</em></strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="How to Filter a List in Python?" width="1400" height="788" src="https://www.youtube.com/embed/3nG4TLkqzf8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p> <iframe src="https://repl.it/@finxter/filterlistpython?lite=true" scrolling="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="400px" frameborder="no"></iframe> </p>
<p>The most Pythonic way of filtering an array is the list comprehension statement <code>[x for x in list if condition]</code>. You can replace <code>condition</code> with any function of <code>x</code> you would like to use as a filtering criterion. </p>
<p>For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement <code>[x for x in list if x&lt;10]</code> to <a href="https://blog.finxter.com/how-to-create-a-python-list/" target="_blank" rel="noreferrer noopener" title="How to Create a Python List?">create a new list</a> with all list elements that are smaller than 10. </p>
<p>Here are three examples of filtering a list:</p>
<ul>
<li>Get elements smaller than eight: <code>[x for x in lst if x&lt;8]</code>.</li>
<li>Get even elements: <code>[x for x in lst if x%2==0]</code>.</li>
<li>Get odd elements: <code>[x for x in lst if x%2]</code>.</li>
</ul>
<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="">lst = [8, 2, 6, 4, 3, 1] # Filter all elements &lt;8
small = [x for x in lst if x&lt;8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)</pre>
<p>The output is:</p>
<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=""># Elements &lt;8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]</pre>
<p>This is the most efficient way of filtering an array and it’s also the most Pythonic one.</p>
<p><strong>Related Article</strong>: <a href="https://blog.finxter.com/how-to-filter-a-list-in-python/" target="_blank" rel="noreferrer noopener" title="How to Filter a List in Python?">How to Filter a List in Python?</a></p>
<h2>Python One-Liners Book</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<figure class="wp-block-image size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img 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="(max-width: 512px) 100vw, 512px" /></a></figure>
<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 “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:</p>
<p><strong>•</strong>&nbsp;&nbsp;Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution<br /><strong>•</strong>&nbsp;&nbsp;Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics<br /><strong>•</strong>&nbsp;&nbsp;Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning<br /><strong>•</strong>&nbsp;&nbsp;Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators<br /><strong>•</strong>&nbsp;&nbsp;Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting</p>
<p>By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners Now!!</em></a></strong></p></p>
</div>


https://www.sickgaming.net/blog/2020/08/28/python-one-line-array/