05-28-2020, 03:34 AM
Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)" width="1400" height="788" src="https://www.youtube.com/embed/fe3nwCR6r2o?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>If you’re like me, you try things first in your code and fix the bugs as they come. One frequent bug in Python is the <code>IndexError: list index out of range</code>. So, what does this error message mean?</p>
<p><strong>The error “<em>list index out of range</em>” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.</strong></p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-74.png" alt="" class="wp-image-8936" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-74.png 852w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x308.png 768w" sizes="(max-width: 852px) 100vw, 852px" /></figure>
<p>Let’s have a look at an example where this error arises:</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 = ['Alice', 'Bob', 'Carl']
print(lst[3])</pre>
<p>The element with index 3 doesn’t exist in the list with three elements. Why is that? The following graphic shows that the maximal index in your list is 2. The call <code>lst[2]</code> would retrieve the <em><strong>third </strong></em>list element <code>'Carl'</code>. Did you try to access the third element with index 3? It’s a common mistake: The index of the third element is 2 because the index of the first list element is 0. </p>
<ul>
<li>lst[0] –> Alice</li>
<li>lst[1] –> Bob</li>
<li>lst[2] –> Carl</li>
<li>lst[3] –> ??? Error ???</li>
</ul>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-1024x576.jpg" alt="" class="wp-image-8937" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p><strong>Try It Yourself:</strong> Before I tell you what to do about it, try to fix the code yourself in our interactive Python shell:</p>
<p> <iframe src="https://trinket.io/embed/python/946c8282bf" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Fix the code in the interactive code shell to get rid of the error message.</em></p>
<h2>How to Fix the IndexError in a For Loop? [General Strategy]</h2>
<p>So, how can you fix the code? Python tells you in which line and on which list the error occurs. </p>
<p>To pin down the exact problem, check the value of the index just before the error occurs. To achieve this, you can print the index that causes the error before you use it on the list. This way, you’ll have your wrong index in the shell right before the error message. </p>
<p>Here’s an example of wrong code that will cause the error to appear:</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=""># WRONG CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): lst[i] # Traceback (most recent call last):
# File "C:\Users\xcent\Desktop\code.py", line 5, in <module>
# lst[i]
# IndexError: list index out of range
</pre>
<p>The error message tells you that the error appears in line 5. So, let’s insert a print statement before that line:</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 = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): print(i) lst[i]</pre>
<p>The result of this code snippet is still an error. But there’s more:</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="">0
1
2
3
4
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 6, in <module> lst[i]
IndexError: list index out of range</pre>
<p>You can now see all indices used to retrieve an element. The final one is the index <code>i=4</code> which points to the fifth element in the list (remember: <em><strong>Python starts indexing at index 0!</strong></em>). But the list has only four elements, so you need to reduce the number of indices you’re iterating over. The correct code is, therefore:</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=""># CORRECT CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)): lst[i]</pre>
<p>Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:</p>
<ul>
<li>Figure out the faulty index just before the error is thrown.</li>
<li>Eliminate the source of the faulty index.</li>
</ul>
<p>IndexError When Modifying a List as You Iterate Over It</p>
<p>The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list:</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="">l=[1,2,3,0,0,1]
for i in range(0, len(l)): if l[i]==0: l.pop(i)</pre>
<p>This code snippet is from a <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/1798796/python-list-index-out-of-range-error" target="_blank">StackOverflow </a>question. The source is simply that the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" target="_blank"><code>list.pop()</code> method</a> removes the element with value 0. All subsequent elements now have a smaller index. But you iterate over all indices up to <code>len(l)-1 = 6-1 = 5</code> and the index 5 does not exist in the list after removing elements in a previous iteration. </p>
<p>You can simply fix this with a short <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">list comprehension</a> statement that accomplishes the same thing:</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="">l = [x for x in l if x]</pre>
<p>Only non-zero elements are included in the list.</p>
<h2>String IndexError: List Index Out of Range</h2>
<p>The error can occur when accessing strings as well:</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="">s = 'Python'
print(s[6])</pre>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-75.png" alt="" class="wp-image-8964" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-75.png 851w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x307.png 768w" sizes="(max-width: 851px) 100vw, 851px" /></figure>
<p>To fix the error for strings, make sure that the index falls between the range <code>0 ... len(s)-1</code> (included):</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="">s = 'Python'
print(s[5])
# n</pre>
<h2>Tuple IndexError: List Index Out of Range</h2>
<p>In fact, the IndexError can occur for all ordered collections where you can use indexing to retrieve certain elements. Thus, it also occurs when accessing tuple indices that do not exist:</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="">s = ('Alice', 'Bob')
print(s[2])</pre>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-76.png" alt="" class="wp-image-8967" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-76.png 852w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x307.png 768w" sizes="(max-width: 852px) 100vw, 852px" /></figure>
<p>Again, start counting with index 0 to get rid of this:</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="">s = ('Alice', 'Bob')
print(s[1])
# Bob</pre>
<p><em><strong>Note</strong>: The index of the last element in any sequence is <code>len(sequence)-1</code>. </em></p>
</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join 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 watch 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></p>
</div>
https://www.sickgaming.net/blog/2020/05/...tupid-bug/
<div><figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python IndexError: List Index Out of Range (How to Fix This Stupid Bug)" width="1400" height="788" src="https://www.youtube.com/embed/fe3nwCR6r2o?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p>If you’re like me, you try things first in your code and fix the bugs as they come. One frequent bug in Python is the <code>IndexError: list index out of range</code>. So, what does this error message mean?</p>
<p><strong>The error “<em>list index out of range</em>” arises if you access invalid indices in your Python list. For example, if you try to access the list element with index 100 but your lists consist only of three elements, Python will throw an IndexError telling you that the list index is out of range.</strong></p>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-74.png" alt="" class="wp-image-8936" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-74.png 852w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x308.png 768w" sizes="(max-width: 852px) 100vw, 852px" /></figure>
<p>Let’s have a look at an example where this error arises:</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 = ['Alice', 'Bob', 'Carl']
print(lst[3])</pre>
<p>The element with index 3 doesn’t exist in the list with three elements. Why is that? The following graphic shows that the maximal index in your list is 2. The call <code>lst[2]</code> would retrieve the <em><strong>third </strong></em>list element <code>'Carl'</code>. Did you try to access the third element with index 3? It’s a common mistake: The index of the third element is 2 because the index of the first list element is 0. </p>
<ul>
<li>lst[0] –> Alice</li>
<li>lst[1] –> Bob</li>
<li>lst[2] –> Carl</li>
<li>lst[3] –> ??? Error ???</li>
</ul>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-1024x576.jpg" alt="" class="wp-image-8937" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/indexing-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p><strong>Try It Yourself:</strong> Before I tell you what to do about it, try to fix the code yourself in our interactive Python shell:</p>
<p> <iframe src="https://trinket.io/embed/python/946c8282bf" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Fix the code in the interactive code shell to get rid of the error message.</em></p>
<h2>How to Fix the IndexError in a For Loop? [General Strategy]</h2>
<p>So, how can you fix the code? Python tells you in which line and on which list the error occurs. </p>
<p>To pin down the exact problem, check the value of the index just before the error occurs. To achieve this, you can print the index that causes the error before you use it on the list. This way, you’ll have your wrong index in the shell right before the error message. </p>
<p>Here’s an example of wrong code that will cause the error to appear:</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=""># WRONG CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): lst[i] # Traceback (most recent call last):
# File "C:\Users\xcent\Desktop\code.py", line 5, in <module>
# lst[i]
# IndexError: list index out of range
</pre>
<p>The error message tells you that the error appears in line 5. So, let’s insert a print statement before that line:</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 = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)+1): print(i) lst[i]</pre>
<p>The result of this code snippet is still an error. But there’s more:</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="">0
1
2
3
4
Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 6, in <module> lst[i]
IndexError: list index out of range</pre>
<p>You can now see all indices used to retrieve an element. The final one is the index <code>i=4</code> which points to the fifth element in the list (remember: <em><strong>Python starts indexing at index 0!</strong></em>). But the list has only four elements, so you need to reduce the number of indices you’re iterating over. The correct code is, therefore:</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=""># CORRECT CODE
lst = ['Alice', 'Bob', 'Ann', 'Carl'] for i in range(len(lst)): lst[i]</pre>
<p>Note that this is a minimal example and it doesn’t make a lot of sense. But the general debugging strategy remains even for advanced code projects:</p>
<ul>
<li>Figure out the faulty index just before the error is thrown.</li>
<li>Eliminate the source of the faulty index.</li>
</ul>
<p>IndexError When Modifying a List as You Iterate Over It</p>
<p>The IndexError also frequently occurs if you iterate over a list but you remove elements as you iterate over the list:</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="">l=[1,2,3,0,0,1]
for i in range(0, len(l)): if l[i]==0: l.pop(i)</pre>
<p>This code snippet is from a <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/1798796/python-list-index-out-of-range-error" target="_blank">StackOverflow </a>question. The source is simply that the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-pop/" target="_blank"><code>list.pop()</code> method</a> removes the element with value 0. All subsequent elements now have a smaller index. But you iterate over all indices up to <code>len(l)-1 = 6-1 = 5</code> and the index 5 does not exist in the list after removing elements in a previous iteration. </p>
<p>You can simply fix this with a short <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">list comprehension</a> statement that accomplishes the same thing:</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="">l = [x for x in l if x]</pre>
<p>Only non-zero elements are included in the list.</p>
<h2>String IndexError: List Index Out of Range</h2>
<p>The error can occur when accessing strings as well:</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="">s = 'Python'
print(s[6])</pre>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-75.png" alt="" class="wp-image-8964" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-75.png 851w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x307.png 768w" sizes="(max-width: 851px) 100vw, 851px" /></figure>
<p>To fix the error for strings, make sure that the index falls between the range <code>0 ... len(s)-1</code> (included):</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="">s = 'Python'
print(s[5])
# n</pre>
<h2>Tuple IndexError: List Index Out of Range</h2>
<p>In fact, the IndexError can occur for all ordered collections where you can use indexing to retrieve certain elements. Thus, it also occurs when accessing tuple indices that do not exist:</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="">s = ('Alice', 'Bob')
print(s[2])</pre>
<figure class="wp-block-image size-large"><img src="https://blog.finxter.com/wp-content/uploads/2020/05/image-76.png" alt="" class="wp-image-8967" srcset="https://blog.finxter.com/wp-content/uploads/2020/05/image-76.png 852w, https://blog.finxter.com/wp-content/uplo...00x120.png 300w, https://blog.finxter.com/wp-content/uplo...68x307.png 768w" sizes="(max-width: 852px) 100vw, 852px" /></figure>
<p>Again, start counting with index 0 to get rid of this:</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="">s = ('Alice', 'Bob')
print(s[1])
# Bob</pre>
<p><em><strong>Note</strong>: The index of the last element in any sequence is <code>len(sequence)-1</code>. </em></p>
</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join 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 watch 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></p>
</div>
https://www.sickgaming.net/blog/2020/05/...tupid-bug/