Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Tuple Comprehension Doesn’t Exist – Use This Instead

#1
Python Tuple Comprehension Doesn’t Exist – Use This Instead

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;392677&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&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 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<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"> 5/5 – (1 vote) </div>
</div>
<p>Python has <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank">list comprehension</a> and <a rel="noreferrer noopener" href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="post" data-id="13313" target="_blank">dictionary comprehension</a> as a concise way to create a list or a dictionary by modifying an existing <a rel="noreferrer noopener" href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank">iterable</a>.</p>
<p>Python also has <a href="https://blog.finxter.com/python-one-line-generator/" data-type="post" data-id="13194" target="_blank" rel="noreferrer noopener">generator expressions</a> that allow you to create an iterable by modifying and potentially filtering each element in another iterable and passing the result in a function, for instance. </p>
<p>Does Python have a tuple comprehension statement? And why or why not? And what to use instead if not?</p>
<p>This tutorial will answer all your questions but first, let’s repeat the three related concepts:</p>
<ul>
<li>list comprehension,</li>
<li>dictionary comprehension,</li>
<li>generator expression</li>
</ul>
<p>If you already know these concepts well, go ahead and skip right to the end of the tutorial! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f9d1-200d-1f4bb.png" alt="?‍?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>List Comprehension</h2>
<p>List comprehension is a compact way of creating lists. The simple formula is <code>[expression + context]</code>.</p>
<ul>
<li><strong>Expression:</strong> What to do with each list element?</li>
<li><strong>Context:</strong> What elements to select? The context consists of an arbitrary number of <code>for</code> and <code>if</code> statements.</li>
</ul>
<p>The example <code>[x+100 for x in range(3)]</code> creates the list <code>[100, 101, 102]</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="">lst = [x for x in range(3)]
print(lst)
# [100, 101, 102]</pre>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="A Simple Introduction to List Comprehension in Python" width="780" height="439" src="https://www.youtube.com/embed/9qsq2Vf48W8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/list-comprehension/" data-type="URL" data-id="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">List Comprehension in Python — A Helpful Illustrated Guide</a></p>
<h2>Dictionary Comprehension</h2>
<p><strong>Dictionary Comprehension</strong> is a concise and memory-efficient way to <strong>create and initialize dictionaries</strong> in one line of Python code. </p>
<p>It consists of two parts: expression and context. </p>
<ul>
<li>The <strong>expression </strong>defines how to map keys to values. </li>
<li>The <strong>context </strong>loops over an iterable using a single-line for loop and defines which (key,value) pairs to include in the new dictionary.</li>
</ul>
<p>The following example shows how to use dictionary comprehension to create a mapping from women to man:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">men = ['Bob', 'Frank', 'Pete']
women = ['Alice', 'Ann', 'Liz'] # One-Liner Dictionary Comprehension
pairs = {w:m for w, m in zip(women, men)} # Print the result to the shell
print(pairs)
# {'Bob': 'Alice', 'Frank': 'Ann', 'Pete': 'Liz'}</pre>
<p>Also, watch the following video for a quick recap on dictionary comprehension:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Dictionary Comprehension - A Powerful One-Liner Tutorial" width="780" height="439" src="https://www.youtube.com/embed/TlEC5Jx72Uc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/python-dictionary-comprehension/" data-type="URL" data-id="https://blog.finxter.com/python-dictionary-comprehension/" target="_blank" rel="noreferrer noopener">Python Dictionary Comprehension: A Powerful One-Liner Tutorial</a></p>
<h2>Set Comprehension</h2>
<p>Set comprehension is a concise way of creating sets in Python using the curly braces notation <code>{expression <strong>for</strong> element <strong>in</strong> context}</code>. </p>
<p>For example, <code>{x <strong>for</strong> x <strong>in</strong> range(10)}</code> creates the set <code>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}</code>. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = {x for x in range(10)}
print(s)
# {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}</pre>
<p>You can optionally add a condition to restrict the context in <code>{expression <strong>for</strong> element <strong>in</strong> context <strong>if</strong> condition}</code>. </p>
<p>For example, <code>{x <strong>for</strong> x <strong>in</strong> range(10) <strong>if </strong>x&gt;5}</code> creates the set <code>{6, 7, 8, 9}</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = {x for x in range(10) if x>5}
print(s)
# {6, 7, 8, 9}</pre>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Set Comprehension -- A Simple Formula Guide" width="780" height="439" src="https://www.youtube.com/embed/sRQcg7l-Sc8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <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">Python Set Comprehension</a></p>
<h2>Generator Expression</h2>
<p class="has-global-color-8-background-color has-background">A generator function is a Pythonic way to create an iterable without explicitly storing it in memory. This reduces memory usage of your code without incurring any additional costs.</p>
<p>The following generator expression shows how you can use a list-comprehension like statement but pass it into the <code><a href="https://blog.finxter.com/python-sum/" data-type="post" data-id="22221" target="_blank" rel="noreferrer noopener">sum()</a></code> function that expects an iterable:</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="">print(sum(random.random() for i in range(1000)))</pre>
<p>The code consists of the following parts:</p>
<ul>
<li>The <code><a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" target="_blank" rel="noreferrer noopener">print()</a></code> function prints the result of the expression to the shell.</li>
<li>The <code><a href="https://blog.finxter.com/python-one-line-sum-list/" target="_blank" rel="noreferrer noopener">sum()</a></code> function sums over all values in the following iterable.</li>
<li>The generator expression <code>random.random() for i in range(1000)</code> generates 1000 random numbers and feeds them into the outer sum() function without creating all of them at once.</li>
</ul>
<p>This way, we still don’t store the whole list of 1000 numbers in memory but create them dynamically.</p>
<p>There are two big advantages to using a generator:</p>
<ul>
<li>(1) You don’t have to create a huge list first and store it in memory but generate the next element as you iterate over it.</li>
<li>(2) It’s shorter and more concise.</li>
</ul>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Learn More</strong>: <a href="https://blog.finxter.com/python-one-line-generator/" data-type="URL" data-id="https://blog.finxter.com/python-one-line-generator/" target="_blank" rel="noreferrer noopener">Python One Line Generator</a></p>
<h2>Tuple Comprehension</h2>
<p>Tuple comprehension such as <code>(x+100 for x in range(3))</code> does not exist in Python for two main reasons:</p>
<ul>
<li><strong>Ambiguity:</strong> The expression <code>(x+100 for x in range(3))</code> for tuple comprehension would be ambiguous because of the parentheses <code>(...)</code>. It could also mean <em>“create a generator expression and use the precedence as indicated by the parenthesis”</em>. In that case, Python wouldn’t know if it should return a tuple or a generator. This is the main reason why tuple comprehension doesn’t exist.</li>
<li><strong>Python Style</strong>: If you want to dynamically create a container data structure and fill it with values, you should use lists. <em>Lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.</em></li>
</ul>
<blockquote class="twitter-tweet">
<p lang="en" dir="ltr"><a href="https://twitter.com/hashtag/python?src=hash&amp;ref_src=twsrc%5Etfw">#python</a> tip: Generally, lists are for looping; tuples for structs. Lists are homogeneous; tuples heterogeneous. Lists for variable length.</p>
<p>&mdash; Raymond Hettinger (@raymondh) <a href="https://twitter.com/raymondh/status/324664257004322817?ref_src=twsrc%5Etfw">April 17, 2013</a></p></blockquote>
<p> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> </p>
<h2>Tuple Comprehension Alternatives</h2>
<p class="has-global-color-8-background-color has-background">You can use the following alternatives instead of tuple comprehension:</p>
<ul class="has-global-color-8-background-color has-background">
<li>tuple(<code>x+100 for x in range(3)</code>) creates the tuple (100, 101, 102) using a generator expression.</li>
<li><code>(1, *[x+100 for x in range(3)])</code> creates the tuple <code>(1, 100, 101, 102)</code> combining manual tuple creation with list comprehension.</li>
</ul>
<p>You can find those two examples in the following code snippet:</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="">
# Tuple Comprehension Alternative 1
t = tuple(x+100 for x in range(3))
print(t)
# (100, 101, 102) # Tuple Comprehension Alternative 2
t = (1, *[x+100 for x in range(3)])
print(t)
# (1, 100, 101, 102) </pre>
<h2>Where to Go From Here?</h2>
<p>Enough theory. Let’s get some practice!</p>
<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>
<p>To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>
<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>If you just want to learn about the freelancing opportunity, feel free to watch my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and learn how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


https://www.sickgaming.net/blog/2022/05/...s-instead/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016