Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python Set to Tuple | Tuple to Set | 3 Easy Ways

#1
Python Set to Tuple | Tuple to Set | 3 Easy Ways

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;689757&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&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;,&quot;font_factor&quot;:&quot;1.25&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" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Problem Formulation</strong>: Given a Python set. How to convert it to a tuple? And how to convert the tuple back to a set?</p>
<p>There are three main ways:</p>
<ul>
<li><strong>Method 1</strong>: To convert a Python <strong>set to a tuple</strong>, use the <code>tuple(my_set)</code> function. </li>
<li><strong>Method 2</strong>: To convert a Python <strong>tuple to a set</strong>, use the <code>set(my_tuple)</code> function. </li>
<li><strong>Method 3</strong>: To convert a Python tuple of mutable elements to a set, use the expression <code>set(tuple(x) for x in my_tuple)</code> to avoid a <code>TypeError</code>.</li>
</ul>
<p>I’ll also give you a <strong>bonus method 4 </strong>that shows you what to do to retain the <strong>ordering information</strong> when converting a tuple to a set—so keep reading! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Method 1: Convert Set to Tuple with tuple()</h2>
<p class="has-global-color-8-background-color has-background">To convert a <a href="https://blog.finxter.com/sets-in-python/" data-type="post" data-id="1908" target="_blank" rel="noreferrer noopener">set</a> to a tuple, pass the set into the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-tuple/" data-type="post" data-id="21575" target="_blank">tuple()</a></code> function. This is a <a rel="noreferrer noopener" href="https://blog.finxter.com/pythons-top-29-built-in-functions-with-examples/" data-type="post" data-id="25777" target="_blank">built-in</a> Python function, so you don’t need to import or <a href="https://blog.finxter.com/how-to-install-xxx-in-python/" data-type="post" data-id="653128" target="_blank" rel="noreferrer noopener">install</a> any library to use it. The return value is a new <a href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank" rel="noreferrer noopener">tuple</a> from the values in the set. </p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Here’s an example where you convert the set <code>{1, 2, 3}</code> to a tuple <code>(1, 2, 3)</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="">my_set = {1, 2, 3}
my_tuple = tuple(my_set)
print(my_tuple)
# (1, 2, 3)</pre>
<p>By the way, here’s an explainer video on this function:</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/python-set-to-tuple-tuple-to-set/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FViJ1E-52hq4%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<h2>Method 2: Convert Tuple to Set with set()</h2>
<p class="has-global-color-8-background-color has-background">To convert a tuple to a <a rel="noreferrer noopener" href="https://blog.finxter.com/sets-in-python/" data-type="post" data-id="1908" target="_blank">set</a>, pass the tuple into the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-set-function/" data-type="post" data-id="23052" target="_blank">set()</a></code> function. This is a <a rel="noreferrer noopener" href="https://blog.finxter.com/pythons-top-29-built-in-functions-with-examples/" data-type="post" data-id="25777" target="_blank">built-in</a> Python function, so you don’t need to import or <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-xxx-in-python/" data-type="post" data-id="653128" target="_blank">install</a> any library. The return value is a new set from the values in the tuple. </p>
<p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Here’s an example where you convert the tuple <code>(1, 2, 3)</code> to a set <code>{1, 2, 3}</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="">my_tuple = (1, 2, 3)
my_set = set(my_tuple)
print(my_set)
# {1, 2, 3}</pre>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/python-set-to-tuple-tuple-to-set/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfZJsKQPlzRg%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<p><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>Problem</strong>: However, the conversion process from a tuple to set doesn’t always work because if you try to convert a tuple of mutable values, Python will raise the <code>TypeError: unhashable type</code>!</p>
<p>Read on to learn more about this problem—and how to resolve it easily: <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
<h2>Method 3: Convert Tuple to Set with Set Comprehension</h2>
<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;" /> A <strong>Python set</strong> is an <strong>unordered collection of unique immutable elements</strong>. Each element must define explicitly or implicitly the <code><a href="https://blog.finxter.com/python-__hash__-magic-method/" data-type="post" data-id="38118">__hash__()</a></code> dunder method, i.e., must be <a href="https://blog.finxter.com/how-to-fix-typeerror-unhashable-type-list/" data-type="post" data-id="465745" target="_blank" rel="noreferrer noopener">hashable</a>.</p>
<p>If you attempt to convert a tuple of <a href="https://blog.finxter.com/mutable-vs-immutable-objects-in-python/" data-type="post" data-id="204090" target="_blank" rel="noreferrer noopener">mutable</a> elements (e.g., <a href="https://blog.finxter.com/python-lists/" data-type="post" data-id="7332" target="_blank" rel="noreferrer noopener">lists</a>) to a set, Python will raise an error such as the <code>TypeError: unhashable type: 'list'</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(my_tuple)
# TypeError: unhashable type: 'list'</pre>
<p class="has-global-color-8-background-color has-background">In this case, you can use <a href="https://blog.finxter.com/brackets-a-simple-introduction-to-set-comprehension-in-python/" data-type="post" data-id="1153">set co</a><a rel="noreferrer noopener" href="https://blog.finxter.com/brackets-a-simple-introduction-to-set-comprehension-in-python/" data-type="post" data-id="1153" target="_blank">m</a><a href="https://blog.finxter.com/brackets-a-simple-introduction-to-set-comprehension-in-python/" data-type="post" data-id="1153">prehension</a> to convert each inner tuple element to an immutable type. For example, the expression <code>set(tuple(x) for x in my_tuple)</code> converts each inner <a href="https://blog.finxter.com/convert-list-to-tuple/" data-type="post" data-id="7862" target="_blank" rel="noreferrer noopener">list to a tuple</a>. The result is a set of immutable tuples.</p>
<p>Here’s the solution to this problem in a minimal code 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="">my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(tuple(x) for x in my_tuple)
print(my_set)
# {(1, 2), (3, 4), (5, 6)}
</pre>
<p>The final “bonus” section introduces another elegant way to retain the ordering information in a set:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="498" height="498" src="https://blog.finxter.com/wp-content/uploads/2022/09/BonusbaadshahGIF.gif" alt="" class="wp-image-689976"/></figure>
</div>
<h2>Bonus Method 4: Enumerate Elements</h2>
<p>Sometimes, you want to associate each set or tuple element with a specific numerical “index” value, i.e., a unique integer identifier. The <code><a href="https://blog.finxter.com/python-enumerate/" data-type="post" data-id="20466" target="_blank" rel="noreferrer noopener">enumerate()</a></code> method to the rescue!</p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube"><a href="https://blog.finxter.com/python-set-to-tuple-tuple-to-set/"><img src="https://blog.finxter.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6SifUNXKWNA%2Fhqdefault.jpg" alt="YouTube Video"></a><figcaption></figcaption></figure>
<ul>
<li>Use <code>tuple(enumerate(my_set))</code> to convert a set to an enumerated tuple. </li>
<li>Use <code>set(enumerate(my_tuple))</code> to convert a tuple to an enumerated set. </li>
</ul>
<p>The result is the respective container data structure with (identifier, value) tuples:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="3, 7" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_set = {'Alice', 'Bob', 'Carl'} my_tuple = tuple(enumerate(my_set))
print(my_tuple)
# ((0, 'Carl'), (1, 'Bob'), (2, 'Alice')) my_set = set(enumerate(('Alice', 'Bob', 'Carl')))
print(my_set)
# {(2, 'Carl'), (0, 'Alice'), (1, 'Bob')}
</pre>
<p>Especially in the case where you convert a tuple to a set, this makes a lot of sense because you can retain the information on the ordering of elements that would be otherwise lost after converting to a set.</p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
<p>Thanks for reading the whole article, my friend! You can join us <a href="https://blog.finxter.com/subscribe/" data-type="page" data-id="1414" target="_blank" rel="noreferrer noopener">here</a> (we have cheat sheets too):</p>
</div>


https://www.sickgaming.net/blog/2022/09/...easy-ways/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016