{"id":70376,"date":"2023-01-19T09:02:00","date_gmt":"2023-01-19T09:02:00","guid":{"rendered":"https:\/\/www.cryptocabaret.com\/?p=70376"},"modified":"2023-01-19T09:02:00","modified_gmt":"2023-01-19T09:02:00","slug":"how-to-fix-an-indexerror-in-python","status":"publish","type":"post","link":"https:\/\/www.cryptocabaret.com\/?p=70376","title":{"rendered":"How to fix an IndexError in Python"},"content":{"rendered":"<p><span class=\"field field--name-title field--type-string field--label-hidden\">How to fix an IndexError in Python<\/span><br \/>\n<span class=\"field field--name-uid field--type-entity-reference field--label-hidden\"><a title=\"View user profile.\" href=\"https:\/\/opensource.com\/users\/vijaytechnicalauthor\" class=\"username\">vijaytechnicalauthor<\/a><\/span><br \/>\n<span class=\"field field--name-created field--type-created field--label-hidden\">Thu, 01\/19\/2023 &#8211; 03:00<\/span><\/p>\n<div class=\"clearfix text-formatted field field--name-body field--type-text-with-summary field--label-hidden field__item\">\n<p>If you use Python, you may have encountered the <code>IndexError<\/code> error in response to some code you&#8217;ve written. The <code>IndexError<\/code> message in Python is a runtime error. To understand what it is and how to fix it, you must first understand what an index is. A Python list (or array or <a href=\"https:\/\/opensource.com\/article\/21\/3\/dictionary-values-python\" target=\"_blank\" rel=\"noopener\">dictionary<\/a>) has an index. The index of an item is its position within a list. To access an item in a list, you use its index. For instance, consider this Python list of fruits:<\/p>\n<pre>\n<code class=\"language-python\">fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]<\/code><\/pre>\n<p>This list&#8217;s range is 5, because an index in Python starts at 0.<\/p>\n<ul>\n<li>apple: 0<\/li>\n<li>banana: 1<\/li>\n<li>orange: 2<\/li>\n<li>pear: 3<\/li>\n<li>grapes: 4<\/li>\n<li>watermelon: 5<\/li>\n<\/ul>\n<p>Suppose you need to print the fruit name <code>pear<\/code> from this list. You can use a simple <code>print<\/code> statement, along with the list name and the index of the item you want to print:<\/p>\n<pre>\n<code class=\"language-python\">&gt;&gt;&gt; fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\n&gt;&gt;&gt; print(fruits[3])\npear\n<\/code><\/pre>\n<h2>What causes an IndexError in Python?<\/h2>\n<p>What if you use an index number outside the range of the list? For example, try to print the index number 6 (which doesn&#8217;t exist):<\/p>\n<pre>\n<code class=\"language-python\">&gt;&gt;&gt; fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\n&gt;&gt;&gt; print(fruits[6])\nTraceback (most recent call last):\n  File \"<string>\", line 2, in <module>\nIndexError: list index out of range\n <\/module><\/string><\/code><\/pre>\n<p>As expected, you get <code>IndexError: list index out of range<\/code> in response.<\/p>\n<h2>How to fix IndexError in Python<\/h2>\n<p>The only solution to fix the <code>IndexError: list index out of range<\/code> error is to ensure that the item you access from a list is within the range of the list. You can accomplish this by using the <code>range()<\/code> an <code>len()<\/code> functions.<\/p>\n<p>The <code>range()<\/code> function outputs sequential numbers, starting with 0 by default, and stopping at the number before the specified value:<\/p>\n<pre>\n<code class=\"language-python\">&gt;&gt;&gt; n = range(6)\n&gt;&gt;&gt; for i in n: \n        print(i)\n0\n1\n2\n3\n4\n5\n5<\/code><\/pre>\n<p>The <code>len()<\/code> function, in the context of a list, returns the number of items in the list:<\/p>\n<pre>\n<code class=\"language-python\">&gt;&gt;&gt; fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\n&gt;&gt;&gt; print(len(fruits))\n6<\/code><\/pre>\n<h2>List index out of range<\/h2>\n<p>By using <code>range()<\/code> and <code>len()<\/code> together, you can prevent index errors. The <code>len()<\/code> function returns the length of the list (6, in this example.) Using that length with <code>range()<\/code> becomes <code>range(6)<\/code>, which returns items at index 0, 1, 2, 3, 4, and 5.<\/p>\n<pre>\n<code class=\"language-python\">fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\nfor i in range(len(fruits)):\n    print(fruits[i])\napple\nbanana\norange\npear\ngrapes\nwatermelon<\/code><\/pre>\n<h2>Fix IndexError in Python loops<\/h2>\n<p>If you&#8217;re not careful, index errors can happen in Python loops. Consider this loop:<\/p>\n<p>\u00a0<\/p>\n<pre>\n<code class=\"language-python\">                                      \n&gt;&gt;&gt; fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\n&gt;&gt;&gt; n = 0\n&gt;&gt;&gt; while n \", line 4, in <module>\nIndexError: list index out of range<\/module><\/code><\/pre>\n<p>The logic seems reasonable. You&#8217;ve defined <code>n<\/code> as a counter variable, and you&#8217;ve set the loop to occur until it equals the length of the list. The length of the list is 6, but its range is 5 (because Python starts its <code>index<\/code> at 0). The condition of the loop is <code>n , and so the<code>while<\/code> loop stops when the value of <code>n<\/code> is equal to 6:<\/code><\/p>\n<ul>\n<li>When n is 0 =&gt; apple<\/li>\n<li>When n is 1 =&gt; banana<\/li>\n<li>When n is 2 =&gt; orange<\/li>\n<li>When n is 3 =&gt; pear<\/li>\n<li>When n is 4 =&gt; grapes<\/li>\n<li>When n is 5 =&gt; watermelon<\/li>\n<li>When n is 6 =&gt; IndexError: list index out of range<\/li>\n<\/ul>\n<p>When <code>n<\/code> is equal to 6, Python produces an <code>IndexError: list index out of range<\/code> error.<\/p>\n<\/p>\n<div class=\"embedded-resource-list callout-float-right\">\n<div class=\"field field--name-title field--type-string field--label-hidden field__item\">More Python resources<\/div>\n<div class=\"field field--name-links field--type-link field--label-hidden field__items\">\n<div class=\"field__item\"><a href=\"https:\/\/www.redhat.com\/en\/topics\/middleware\/what-is-ide?intcmp=7016000000127cYAAQ\">What is an IDE?<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/downloads\/cheat-sheet-python-37-beginners?intcmp=7016000000127cYAAQ\">Cheat sheet: Python 3.7 for beginners<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/resources\/python\/gui-frameworks?intcmp=7016000000127cYAAQ\">Top Python GUI frameworks<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/downloads\/7-essential-pypi-libraries?intcmp=7016000000127cYAAQ\">Download: 7 essential PyPI libraries<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/developers.redhat.com\/?intcmp=7016000000127cYAAQ\">Red Hat Developers<\/a><\/div>\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/tags\/python?intcmp=7016000000127cYAAQ\">Latest Python articles<\/a><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<h2>Solution<\/h2>\n<p>To avoid this error within Python loops, use only the while loop at the last index of the list. This is one number short of the list&#8217;s length:<\/p>\n<pre>\n<code class=\"language-python\">                                       \n&gt;&gt;&gt; fruits = [\"apple\", \"banana\", \"orange\", \"pear\", \"grapes\", \"watermelon\"]\n&gt;&gt;&gt; n = 0\n&gt;&gt;&gt; while n <\/code><\/pre>\n<p>There&#8217;s another way to fix, this too, but I leave that to you to discover.<\/p>\n<h2>No more Python index errors<\/h2>\n<p>The ultimate cause of <code>IndexError<\/code> is an attempt to access an item that doesn&#8217;t exist within a data structure. Using the <code>range()<\/code> and <code>len()<\/code> functions is one solution, and of course keep in mind that Python starts counting at 0, not 1.<\/p>\n<\/div>\n<div class=\"clearfix text-formatted field field--name-field-article-subhead field--type-text-long field--label-hidden field__item\">\n<p>Follow this Python tutorial to learn how to solve an IndexError.<\/p>\n<\/div>\n<div class=\"field field--name-field-lead-image field--type-entity-reference field--label-hidden field__item\">\n<article class=\"media media--type-image media--view-mode-caption\">\n<div class=\"field field--name-field-media-image field--type-image field--label-hidden field__item\">  <img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/www.cryptocabaret.com\/wp-content\/uploads\/2023\/01\/coffee_python.jpg\" width=\"520\" height=\"293\" alt=\"How to write a web service using Python Flask\" title=\"How to write a web service using Python Flask\"><\/div>\n<div class=\"field field--name-field-caption field--type-text-long field--label-hidden caption field__item\"><span class=\"caption__byline\">Image by: <\/span><\/p>\n<p>Yuko Honda on Flickr. CC BY-SA 2.0<\/p>\n<\/div>\n<\/article>\n<\/div>\n<div class=\"field field--name-field-tags field--type-entity-reference field--label-hidden field__items\">\n<div class=\"field__item\"><a href=\"https:\/\/opensource.com\/tags\/python\" hreflang=\"en\">Python<\/a><\/div>\n<\/p><\/div>\n<div class=\"hidden field field--name-field-listicle-title field--type-string field--label-hidden field__item\">What to read next<\/div>\n<div class=\"field field--name-field-default-license field--type-list-string field--label-hidden field__item\"><a rel=\"license\" href=\"http:\/\/creativecommons.org\/licenses\/by-sa\/4.0\/\"><br \/>\n        <img decoding=\"async\" alt=\"Creative Commons License\" src=\"https:\/\/www.cryptocabaret.com\/wp-content\/uploads\/2023\/01\/cc-by-sa--28.png\" title=\"This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.\"><\/a>This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.<\/div>\n<section class=\"field field--name-field-comments field--type-comment field--label-hidden comment-wrapper\">\n<div class=\"comments__count\">\n<div class=\"login\"><a href=\"https:\/\/opensource.com\/user\/register?absolute=1\">Register<\/a> or <a href=\"https:\/\/opensource.com\/user\/login?destination=\/feed&amp;absolute=1\">Login<\/a> to post a comment.<\/div>\n<\/p><\/div>\n<\/section>\n<p class=\"wpematico_credit\"><small>Powered by <a href=\"http:\/\/www.wpematico.com\" target=\"_blank\" rel=\"noopener\">WPeMatico<\/a><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>How to fix an IndexError in Python vijaytechnicalauthor Thu, 01\/19\/2023 &#8211; 03:00 If you use Python, you may have encountered the IndexError error in response to some code you&#8217;ve written. The IndexError message in Python is a runtime error. To understand what it is and how to fix it, you must first understand what an [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":70377,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[307],"tags":[],"class_list":["post-70376","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-open-source"],"_links":{"self":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts\/70376","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=70376"}],"version-history":[{"count":0,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/posts\/70376\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=\/wp\/v2\/media\/70377"}],"wp:attachment":[{"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=70376"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=70376"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.cryptocabaret.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=70376"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}