[Tut] How to Create a Python Tuple of Size n? - 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] How to Create a Python Tuple of Size n? (/thread-99859.html) |
[Tut] How to Create a Python Tuple of Size n? - xSicKxBot - 08-26-2022 How to Create a Python Tuple of Size n? <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"606497","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}"> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 142.5px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (1 vote) </div> </div> <p class="has-global-color-8-background-color has-background">Use the tuple concatenation operation <code>*</code> with a tuple with one element <code>(42,)</code> as a right operand and the number of repetitions of this element as a left operand. For example, the expression <code>(42,) * n</code> creates the tuple <code>(42, 42, 42, 42, 42)</code> for <code>n=5</code>.</p> <p>Let’s play with an interactive code shell before you’ll dive into the detailed solution!</p> <p> <iframe loading="lazy" src="https://trinket.io/embed/python/2f2185e99e" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p> <p><em><strong>Exercise</strong>: Initialize the tuple with <code>n=20</code> placeholder elements <code>-1</code> and run the code. </em></p> <hr class="wp-block-separator has-css-opacity"/> <h2>Problem Formulation</h2> <p>Next, you’ll learn about the more formal problem and dive into the step-by-step solution.</p> <p><strong>Problem</strong>: Given an integer <code>n</code>. How to initialize a tuple with <code>n</code> placeholder elements (e.g., <code>42</code>)?</p> <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=""># n=0 --> () # n=1 --> (42,) # n=5 --> (42, 42, 42, 42, 42)</pre> <h2>Example 1 – Tuple Concatenation</h2> <p>Use the tuple concatenation operation <code>*</code> with a tuple with one element <code>(42,)</code> as right operand and the number of repetitions of this element as left operand. For example, the expression <code>(42,) * n</code> creates the tuple <code>(42, 42, 42, 42, 42)</code> for <code>n=5</code>.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">n = 5 t = (42,) * n print(t) # (42, 42, 42, 42, 42)</pre> <p>Note that you cannot change the values of a tuple, once created, because unlike lists tuples are <a rel="noreferrer noopener" href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank">immutable</a>. For example, trying to overwrite the third tuple value will yield a <code>TypeError: 'tuple' object does not support item assignment</code>.</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2,6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> x = (42,) * 5 >>> x[0] = 'Alice' Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> x[0] = 'Alice' TypeError: 'tuple' object does not support item assignment</pre> <h2>Example 2 – N-Ary Tuple Concatenation</h2> <p class="has-global-color-8-background-color has-background">You can also use a generalization of the <strong><em>unary</em></strong> tuple concatenation — I call it <strong><em>n-ary tuple concatenation</em></strong> — to create a tuple of size <code>n</code>. For example, given a tuple <code>t</code> of size 3, you can create a tuple of size 9 by multiplying it with the integer 3 like so: <code>t * 3</code>. </p> <p>Here’s an example:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">simple_tuple = ('Alice', 42, 3.14) complex_tuple = simple_tuple * 3 print(complex_tuple) # ('Alice', 42, 3.14, 'Alice', 42, 3.14, 'Alice', 42, 3.14)</pre> <h2>Example 3 – Tuple From List</h2> <p class="has-global-color-8-background-color has-background">This approach is simple: First, create a list of size n. Second, pass that list into the <code><a href="https://blog.finxter.com/python-tuple/" data-type="post" data-id="21575" target="_blank" rel="noreferrer noopener">tuple()</a></code> function to create a tuple of size <code>n</code>. </p> <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="">n = 100 # 1. Create list of size n lst = [42] * n # 2. Change value in (mutable) list lst[2] = 'Alice' # 3. Create tuple from list AFTER modification t = tuple(lst) # 4. Print tuple print(t) # (42, 42, 'Alice', 42, 42, ...)</pre> <p class="has-base-background-color has-background"><strong>Recommended Tutorial</strong>: <a href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" data-type="post" data-id="10466">Create a List </a><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">o</a><a href="https://blog.finxter.com/how-to-create-a-python-list-of-size-n/" data-type="post" data-id="10466">f Size n</a></p> </p> <h2>Example 4 – Generator Expression (List Comprehension)</h2> <p class="has-global-color-8-background-color has-background">You can pass a <a href="https://blog.finxter.com/python-one-line-generator/" data-type="post" data-id="13194" target="_blank" rel="noreferrer noopener">generator expression</a> into Python’s built-in <code><a href="https://blog.finxter.com/python-tuple/" data-type="post" data-id="21575" target="_blank" rel="noreferrer noopener">tuple()</a></code> function to dynamically create a tuple of elements, given another iterable. For example, the expression <code>tuple(i**2 for i in range(10))</code> creates a tuple with ten square numbers.</p> <p>Here’s the code snippet for copy&paste:</p> <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 = tuple(i**2 for i in range(10)) print(x) # (0, 1, 4, 9, 16, 25, 36, 49, 64, 81)</pre> <p>In case you need some background on this terrific Python feature, check out my article on <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank">List Comprehension</a> and my <a rel="noreferrer noopener" href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank">best-selling</a> Python textbook on writing super condensed and concise Python code:</p> <h2>Python One-Liners Book: Master the Single Line First!</h2> <p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p> <div class="wp-block-image"> <figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img 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="(max-width: 512px) 100vw, 512px" /></a></figure> </div> <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”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>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 (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p> <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’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> <p>You’ll also learn how to:</p> <ul> <li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li> <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> <li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li> <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> <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> </ul> <p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, 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 on Amazon!!</em></a></strong></p> </div> https://www.sickgaming.net/blog/2022/08/23/how-to-create-a-python-tuple-of-size-n/ |