[Tut] (Fixed) Python TypeError ‘bool’ object is not subscriptable - 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] (Fixed) Python TypeError ‘bool’ object is not subscriptable (/thread-100014.html) |
[Tut] (Fixed) Python TypeError ‘bool’ object is not subscriptable - xSicKxBot - 10-02-2022 (Fixed) Python TypeError ‘bool’ object is not subscriptable <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"742932","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> <div class="wp-block-image"> <figure class="aligncenter size-full"><img loading="lazy" width="761" height="225" src="https://blog.finxter.com/wp-content/uploads/2022/10/image-11.png" alt="" class="wp-image-742949" srcset="https://blog.finxter.com/wp-content/uploads/2022/10/image-11.png 761w, https://blog.finxter.com/wp-content/uploads/2022/10/image-11-300x89.png 300w" sizes="(max-width: 761px) 100vw, 761px" /></figure> </div> <h2>Problem Formulation</h2> <p>Consider the following minimal example where a <code>TypeError: 'bool' object is not subscriptable</code> occurs:</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="">boo = True boo[0] # or: boo[3:6]</pre> <p>This yields the following output:</p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> boo[0] TypeError: 'bool' object is not subscriptable</pre> <h2>Solution Overview</h2> <p class="has-global-color-8-background-color has-background">Python raises the <code>TypeError: 'bool' object is not subscriptable</code> if you use indexing or slicing with the square bracket notation on a Boolean variable. However, the Boolean type is not indexable and you cannot slice it—it’s not <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>In other words, the Boolean class doesn’t define the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-__getitem__-magic-method/" data-type="post" data-id="125374" target="_blank">__getitem__()</a></code> method. </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="">boo = True boo[0] # Error! boo[3:6] # Error! boo[-1] # Error! boo[:] # Error!</pre> <p>You can fix this error by</p> <ol> <li>converting the Boolean to a string using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-str-function/" data-type="post" data-id="23735" target="_blank">str()</a></code> function because strings are subscriptable,</li> <li>removing the indexing or slicing call,</li> <li>defining a dummy <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-__getitem__-magic-method/" data-type="post" data-id="125374" target="_blank">__getitem__()</a></code> method for a custom “Boolean wrapper class”.</li> </ol> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Related Tutorials</strong>: Check out our tutorials on <a href="https://blog.finxter.com/daily-python-puzzle-list-indexing/" data-type="post" data-id="84" target="_blank" rel="noreferrer noopener">indexing</a> and <a href="https://blog.finxter.com/introduction-to-slicing-in-python/" data-type="post" data-id="731" target="_blank" rel="noreferrer noopener">slicing</a> on the Finxter blog to improve your skills!</p> <h2>Method 1: Convert Boolean to a String</h2> <p>If you want to access individual characters of the “Boolean” strings <code>"True"</code> and <code>"False"</code>, consider converting the Boolean to a string using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-str-function/" data-type="post" data-id="23735" target="_blank">str()</a></code> built-in function. A string is subscriptable so the error will not occur when trying to index or slice the converted string.</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="">boo = True boo_string = str(boo) print(boo_string[0]) # T print(boo_string[1:-1]) # ru </pre> <h2>Method 2: Put Boolean Into List</h2> <p>A simple way to resolve this error is to put the Boolean into a list that is subscriptable—that is you can use indexing or slicing on lists that define the <code>__getitem__()</code> magic method. </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="">bools = [True, True, True, False, False, False, True, False] print(bools[-1]) # False print(bools[3:-3]) # [False, False]</pre> <h2>Method 3: Define the __getitem__() Magic Method</h2> <p>You can also define your own wrapper type around the Boolean variable that defines a dunder method for <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-__getitem__-magic-method/" data-type="post" data-id="125374" target="_blank">__getitem__()</a></code> so that every indexing or slicing operation returns a specified value as defined in the dunder method. </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="">class MyBool: def __init__(self, boo): self.boo = boo def __getitem__(self, index): return self.boo my_boolean = MyBool(True) print(my_boolean[0]) # True print(my_boolean[:-1]) # True </pre> <p>This hack is generally not recommended, I included it just for comprehensibility and to teach you something new. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f609.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <h2>Summary</h2> <p class="has-global-color-8-background-color has-background"><strong>The error message “<code>TypeError: 'boolean' object is not subscriptable</code>” happens if you access a boolean <code>boo</code> like a list such as <code>boo[0]</code> or <code>boo[1:4]</code>. To solve this error, avoid using slicing or indexing on a Boolean or use a subscriptable object such as lists or strings.</strong></p> </div> https://www.sickgaming.net/blog/2022/10/01/fixed-python-typeerror-bool-object-is-not-subscriptable/ |