Open-source News

How to fix an IndexError in Python

opensource.com - Thu, 01/19/2023 - 16:00
How to fix an IndexError in Python vijaytechnicalauthor Thu, 01/19/2023 - 03:00

If you use Python, you may have encountered the IndexError error in response to some code you'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 index is. A Python list (or array or dictionary) 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:

fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"]

This list's range is 5, because an index in Python starts at 0.

  • apple: 0
  • banana: 1
  • orange: 2
  • pear: 3
  • grapes: 4
  • watermelon: 5

Suppose you need to print the fruit name pear from this list. You can use a simple print statement, along with the list name and the index of the item you want to print:

>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] >>> print(fruits[3]) pear What causes an IndexError in Python?

What if you use an index number outside the range of the list? For example, try to print the index number 6 (which doesn't exist):

>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] >>> print(fruits[6]) Traceback (most recent call last): File "", line 2, in IndexError: list index out of range

As expected, you get IndexError: list index out of range in response.

How to fix IndexError in Python

The only solution to fix the IndexError: list index out of range 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 range() an len() functions.

The range() function outputs sequential numbers, starting with 0 by default, and stopping at the number before the specified value:

>>> n = range(6) >>> for i in n: print(i) 0 1 2 3 4 5 5

The len() function, in the context of a list, returns the number of items in the list:

>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] >>> print(len(fruits)) 6List index out of range

By using range() and len() together, you can prevent index errors. The len() function returns the length of the list (6, in this example.) Using that length with range() becomes range(6), which returns items at index 0, 1, 2, 3, 4, and 5.

fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] for i in range(len(fruits)): print(fruits[i]) apple banana orange pear grapes watermelonFix IndexError in Python loops

If you're not careful, index errors can happen in Python loops. Consider this loop:

 

>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] >>> n = 0 >>> while n <= len(fruits) print(fruits[n]) n+=1 apple banana orange pear grapes watermelon Traceback (most recent call last): File "", line 4, in IndexError: list index out of range

The logic seems reasonable. You've defined n as a counter variable, and you'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 index at 0). The condition of the loop is n <= 6, and so thewhile loop stops when the value of n is equal to 6:

  • When n is 0 => apple
  • When n is 1 => banana
  • When n is 2 => orange
  • When n is 3 => pear
  • When n is 4 => grapes
  • When n is 5 => watermelon
  • When n is 6 => IndexError: list index out of range

When n is equal to 6, Python produces an IndexError: list index out of range error.

More Python resources What is an IDE? Cheat sheet: Python 3.7 for beginners Top Python GUI frameworks Download: 7 essential PyPI libraries Red Hat Developers Latest Python articles Solution

To avoid this error within Python loops, use only the < ("less than") operator, stopping the while loop at the last index of the list. This is one number short of the list's length:

>>> fruits = ["apple", "banana", "orange", "pear", "grapes", "watermelon"] >>> n = 0 >>> while n < len(fruits) print(fruits[n]) n+=1 apple banana orange pear grapes watermelon

There's another way to fix, this too, but I leave that to you to discover.

No more Python index errors

The ultimate cause of IndexError is an attempt to access an item that doesn't exist within a data structure. Using the range() and len() functions is one solution, and of course keep in mind that Python starts counting at 0, not 1.

Follow this Python tutorial to learn how to solve an IndexError.

Image by:

Yuko Honda on Flickr. CC BY-SA 2.0

Python What to read next This work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License. Register or Login to post a comment.

How to Install Sublime Text 4 in Linux

Tecmint - Thu, 01/19/2023 - 13:23
The post How to Install Sublime Text 4 in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .

If you’re not a terminal lover, you might not like using the popular command-line text editors Vi or Vim. Speaking of graphical-based, Sublime Text is one of the most preferred cross-platform proprietary-based text and

The post How to Install Sublime Text 4 in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides.

AVX-512 Performance Comparison: AMD Genoa vs. Intel Sapphire Rapids & Ice Lake

Phoronix - Thu, 01/19/2023 - 02:16
With last week's launch of Intel's 4th Gen Xeon Scalable Sapphire Rapids server processors, Intel heavily talked up the shiny new accelerators and the big performance potential of AMX, but not really showcased and only heard through the grapevine was the improved AVX-512 implementation found with these new processors. With Sapphire Rapids there is reduced penalties from engaging AVX-512 -- and for some AVX-512 instructions, no longer any measurable impact -- compared to prior generation Xeon processors. In this article is a look at the performance for a wide variety of workloads with AVX-512 on/off not just for Sapphire Rapids but also for prior generation Ice Lake as well as AMD's new EPYC 4th Gen "Genoa" processors where they have introduced AVX-512 for the first time.

Fedora 38 Change Approved To Mandate Quicker Reboots/Shutdowns

Phoronix - Wed, 01/18/2023 - 23:51
Last month a change proposal was filed for aiming to yield faster reboots and shutdowns of Fedora Linux by shortening the time window that services can block the shutdown process. A modified version of that change proposal has now been cleared by the Fedora Engineering and Steering Committee...

Intel Emerald Rapids Driver Additions Begin Landing In Linux 6.2

Phoronix - Wed, 01/18/2023 - 23:26
Starting to appear in Linux 6.2 as part of the various "fixes" pull requests are new device IDs for adding Intel 5th Gen Xeon Scalable "Emerald Rapids" support for drivers not requiring any other code changes over the existing Sapphire Rapids code path.s..

Pages