Sick Gaming
[Tut] Python Unpacking [Ultimate Guide] - 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 Unpacking [Ultimate Guide] (/thread-99513.html)



[Tut] Python Unpacking [Ultimate Guide] - xSicKxBot - 06-06-2022

Python Unpacking [Ultimate Guide]

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;396420&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>In this article, you’ll learn about the following topics:</p>
<ul>
<li>List unpacking in Python</li>
<li>Tuple unpacking in Python</li>
<li>String unpacking in Python</li>
<li>ValueError: too many values to unpack (expected k)</li>
<li>ValueError: not enough values to unpack (expected x, got y)</li>
<li>Unpacking nested list or tuple</li>
<li>Unpacking underscore</li>
<li>Unpacking asterisk</li>
</ul>
<h2>Sequence Unpacking Basics</h2>
<p>Python allows you to assign <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterables</a> such as lists and tuples and assign them to multiple variables. </p>
<p class="has-global-color-8-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><em>Iterable unpacking</em></strong> or <strong><em>sequence unpacking</em></strong> is the process of assigning the elements of an iterable (e.g., <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank">tuple</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank">list</a>, <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-methods/" data-type="post" data-id="25974" target="_blank">string</a>) to multiple variables. For it to work, you need to have enough variables to capture the number of elements in the iterable.</p>
</p>
<h2>Python List Unpacking</h2>
<p class="has-global-color-8-background-color has-background"><strong>List unpacking</strong> is the process of assigning <em>k</em> elements of a list to <em>k</em> different variables in a <a href="https://blog.finxter.com/python-one-line-x/" data-type="post" data-id="10612" target="_blank" rel="noreferrer noopener">single line of code</a>.</p>
<p>In the following example, you unpack the three elements in the list <code>[1, 2, 3]</code> into variables <code>a</code>, <code>b</code>, and <code>c</code>. Each variable captures one list element after the unpacking operation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># List Unpacking
a, b, c = [1, 2, 3] print(a)
# 1 print(b)
# 2 print©
# 3</pre>
<h2>ValueError: too many values to unpack (expected k)</h2>
<p>If the list has too many values to unpack — i.e., the number of elements in the list is larger than the variables to assign them to — Python will raise a <code>ValueError: too many values to unpack (expected k)</code> whereas k is the number of variables on the left-hand side of the <a href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217">assignment operation</a>.</p>
<p>This can be seen in the following code snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a, b, c = [1, 2, 3, 4] '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 1, in &lt;module> a, b, c = [1, 2, 3, 4]
ValueError: too many values to unpack (expected 3) '''</pre>
<p class="has-global-color-8-background-color has-background">To resolve the <code>ValueError: too many values to unpack (expected k)</code>, make sure that the number of elements on the right and left-hand sides of the unpacking operation is the same.</p>
<p>Per convention, if you don’t need to store a certain list element in a variable, you can use the “throw-away” underscore variable name <code>_</code>.</p>
<p>Here’s the same example resolved using the underscore name:</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="">a, b, _, c = [1, 2, 3, 4] print(a)
# 1 print(b)
# 2 print©
# 4
</pre>
<p>Alternatively, you can also use the asterisk operator on the left-hand side as will be explained at the end of this article—so keep reading! <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;" /></p>
<h2>ValueError: not enough values to unpack (expected x, got y)</h2>
<p>If the iterable has too few values to unpack — i.e., the number of elements in the iterable is larger than the variables to assign them to — Python will raise a <code>ValueError: not enough values to unpack (expected x, got y)</code> whereas <code>x</code> is the number of variables on the left-hand side of the <a href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217">assignment operation</a> and <code>y</code> is the number of elements in the iterable.</p>
<p>This can be seen in the following code snippet:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a, b, c, d = [1, 2, 3] '''
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 1, in &lt;module> a, b, c, d = [1, 2, 3]
ValueError: not enough values to unpack (expected 4, got 3) '''
</pre>
<p class="has-global-color-8-background-color has-background">To resolve the <code><code>ValueError: not enough values to unpack (expected x, got y)</code></code>, make sure that the number of elements on the right and left-hand sides of the unpacking operation is the same.</p>
<h2>Python Tuple Unpacking</h2>
<p class="has-global-color-8-background-color has-background"><strong>Tuple unpacking</strong> is the process of assigning <em>k</em> elements of a tuple to <em>k</em> different variables in a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-liners/" data-type="post" data-id="13555" target="_blank">single line of code</a>.</p>
<p>In the following example, you unpack the three elements in the tuple <code>(1, 2, 3)</code> into variables <code>a</code>, <code>b</code>, and <code>c</code>. Each variable captures one tuple element after the unpacking operation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Tuple Unpacking
a, b, c = (1, 2, 3) print(a)
# 1 print(b)
# 2 print©
# 3</pre>
<p>Note that the parentheses of tuples are optional, so you can omit them to obtain the same behavior with even fewer syntax overhead as shown in the following example. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f60a.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Tuple Unpacking
a, b, c = 1, 2, 3 print(a)
# 1 print(b)
# 2 print©
# 3</pre>
<h2>Python String Unpacking</h2>
<p class="has-global-color-8-background-color has-background"><strong>String unpacking</strong> is the process of assigning <em>k</em> characters of a string to <em>k</em> different variables in a <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">single line of code</a>.</p>
<p>In the following example, you unpack the seven characters in the string <code>'finxter'</code> into variables <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>e</code>, <code>f</code>, and <code>g</code>. Each variable captures one character from the string, in order, after the unpacking operation.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1-2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># String Unpacking
a, b, c, d, e, f, g = 'finxter' print(a)
print(b)
print©
print(d)
print(e)
print(f)
print(g) '''
f
i
n
x
t
e
r '''
</pre>
<h2 id="unpack-a-nested-tuple-and-list">Python Unpacking Nested List or Tuple</h2>
<p>You can also unpack a nested iterable (e.g., <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-of-lists/" data-type="post" data-id="7890" target="_blank">list of lists</a>, or <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-convert-tuple-of-tuples-to-list-of-lists-in-python/" data-type="post" data-id="388975" target="_blank">tuple of tuples</a>). </p>
<p>The simple case is where one variable (in our example <code>c</code>) captures the whole inner list (in our example <code>[3, 4, 5]</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="">lst = [1, 2, [3, 4, 5]]
a, b, c = lst print(a)
print(b)
print© '''
1
2
[3, 4, 5] '''
</pre>
<p><strong><em>But how can you assign the elements of the inner list to variables as well?</em></strong> </p>
<p>This can be done by setting up a parallel structure on the left and right sides of the equation using parentheses <code>(...)</code> or square brackets <code>[...]</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="">lst = [1, 2, [3, 4, 5]]
a, b, [c, d, e] = lst print(a)
print(b)
print©
print(d)
print(e) '''
1
2
3
4
5 '''
</pre>
<p>The simple heuristic to understand what is going on here is:<strong><em> parallel structures</em></strong>!</p>
<h2>Python Unpacking Underscore</h2>
<p class="has-global-color-8-background-color has-background">The underscore <code>_</code> in Python behaves like a normal variable name. Per convention, it is used if you don’t actually care about the value stored in it but just use it to capture all values from an iterable in a syntactically correct way. </p>
<p>Here’s a simple example:</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="">lst = ['Alice', 'Bob', 'Carl'] a, _, c = lst print(a)
print(_)
print© '''
Alice
Bob
Carl '''
</pre>
<h2>Python Unpacking Asterisk</h2>
<p>You can use the <a href="https://blog.finxter.com/what-is-asterisk-in-python/" data-type="post" data-id="1344" target="_blank" rel="noreferrer noopener">asterisk operator</a> * on the left-hand side of the equation to unpack multiple elements into a single variable. </p>
<p>This way, you can overcome the <code>ValueError: too many values to unpack</code> when there are <strong><em>more values in the iterable than there are variables</em></strong> to capture them.</p>
<p>Here’s an example where we capture two elements <code>2</code> and <code>3</code> in one variable <code>b</code> using the asterisk operator as a prefix in <code>*b</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="">a, *b, c = [1, 2, 3, 4] print(a)
print(b)
print© '''
1
[2, 3]
4 '''
</pre>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/26a1.png" alt="⚡" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: This only works in Python 3 but not in Python 2. Here’s how to <a href="https://blog.finxter.com/how-to-check-your-python-version/" data-type="URL" data-id="https://blog.finxter.com/how-to-check-your-python-version/" target="_blank" rel="noreferrer noopener">check your Python version</a>.</p>
<p>Python will automatically assign the values in the iterable to the variables so that the asterisked’ variable captures all remaining elements.</p>
<p>In the following example, the asterisked variable <code>*a</code> captures all the remaining values that cannot be captured by the non-asterisked variables:</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="">*a, b, c = [1, 2, 3, 4, 5] print(a)
print(b)
print© '''
[1, 2, 3]
4
5 '''
</pre>
<p>No matter how many elements are captured by the asterisked variable, they will always be stored as a list (even if a single variable would be enough):</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="">first, *_, last = ['Alice', 'Bob', 'Carl'] print(first)
print(_)
print(last) '''
Alice
['Bob']
Carl '''
</pre>
<p>However, you cannot use multiple asterisk operators in the same expression or Python wouldn’t know which iterable elements to assign to which variables. </p>
<p>The following screenshot shows how Python doesn’t compile with the warning <em><strong>“SyntaxError: multiple starred expressions in assignment”</strong></em>. </p>
<figure class="wp-block-image size-full"><img loading="lazy" width="740" height="375" src="https://blog.finxter.com/wp-content/uploads/2022/05/image-342.png" alt="" class="wp-image-396475" srcset="https://blog.finxter.com/wp-content/uploads/2022/05/image-342.png 740w, https://blog.finxter.com/wp-content/uploads/2022/05/image-342-300x152.png 300w" sizes="(max-width: 740px) 100vw, 740px" /></figure>
<p>If you’re completely uninterested in all but a couple of elements of a large list, you can combine the throw-away underscore operator <code>_</code> with the asterisk operator <code>*</code> like so <code>*_</code>. Using this approach, the underscore will capture all the unnecessary elements from the <a href="https://blog.finxter.com/iterators-iterables-and-itertools/" data-type="post" data-id="29507" target="_blank" rel="noreferrer noopener">iterable</a>.</p>
</p>
<p>This can be seen in the following example:</p>
<h2>How to Capture First and Last Element of an Iterable in Variable [Example]</h2>
<p>Here’s an example of this:</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="">first, *_, last = list(range(100)) print(first, last)
# 0 99
</pre>
<p>All list elements 1 to 98 (included) are now stored in the throw-away variable <code>_</code>. </p>
<p>Python assigns an empty list to the asterisked variable if no additional elements can be assigned to it because all are already assigned to other variables:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">a, b, *c = [1, 2] print(a)
print(b)
print© '''
1
2
[] '''
</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/29/python-unpacking-ultimate-guide/