IndexError: list index out of range

Estimated reading time: 3 minutes

Are you working with lists and getting the error IndexError: list index out of range while using Python? There is a very simple explanation to this, and its fix is very easy.

First of all lets understand what is going on with the list.

Traceback (most recent call last):
  File "C:/Users/haugh/OneDrive/dataanalyticsireland/YOUTUBE/IndexError_list_index_out_of_range/INDEX_ERROR_LIST_INDEX_OUT_OF_RANGE.py", line 4, in <module>
    print(data[4])
IndexError: list index out of range

Lists and their index values

In the below list, we have outputted its values and index values.

data = ['a','b','c','d']
for (i,item) in enumerate(data, start=0): #===> Loops through list and applies index values starting at zero
    print(i,item)

Output:
0 a
1 b
2 c
3 d

Process finished with exit code 0

As can be seen the program returns the list values and their indexes. Note that the index starts at zero as we have set start=0.

Start=0 can be set to any value you like, as can be seen here:

data = ['a','b','c','d']
for (i,item) in enumerate(data, start=1): #===> Loops through list and applies index values starting at zero
    print(i,item)

Output:
1 a
2 b
3 c
4 d

Process finished with exit code 0

OR

data = ['a','b','c','d']
for (i,item) in enumerate(data, start=22): #===> Loops through list and applies index values starting at zero
    print(i,item)

Output:
22 a
23 b
24 c
25 d

Process finished with exit code 0

The purpose of the index value is to tell the program where to start its index from, if left empty it starts at zero.

Lists and the no of index values

In the above examples the index values all occur on four rows.

This is important as when you are looping through the rows, it will not go beyond the length of the rows.

So in this example the enumerate function specifically counts the no rows and stores the index values with each, and then loops through the list till it hits the last one, without error.

data = ['a','b','c','d']
for (i,item) in enumerate(data, start=0): #===> Loops through list and applies index values starting at zero
    print(i,item)

Output:
0 a
1 b
2 c
3 d

Process finished with exit code 0

How to fix the error IndexError: list index out of range

So the reason we get the below is that the line print(data[4]) is looking for the row with index value 4, but we know that from observation that does not exist.

To fix this we would change the value 4 in print(data[4]) to any of 0,1,2,3, as they are the index values associated with the list.

data = ['a','b','c','d']
for (i,item) in enumerate(data, start=0): #===> Loops through list and applies index values starting at zero
    print(i,item)
print(data[4])

Output:
Traceback (most recent call last):
  File "C:/Users/haugh/OneDrive/dataanalyticsireland/YOUTUBE/IndexError_list_index_out_of_range/INDEX_ERROR_LIST_INDEX_OUT_OF_RANGE.py", line 4, in <module>
    print(data[4])
IndexError: list index out of range
0 a
1 b
2 c
3 d

Applying a correct valid index value:
data = ['a','b','c','d']
for (i,item) in enumerate(data, start=0): #===> Loops through list and applies index values starting at zero
    print(i,item)
print(data[3])

Yields with no error:
0 a
1 b
2 c
3 d
d

So in summary when working with lists and their index values it is important:

(A) Understand the length of your list.

(B) Where your index values start and finish.

This error is easily fixable, but in your code you just need to make sure that you referencing values that are in the range of your index values.

YouTube channel lists – Python Data Cleansing

Ever had a process where you received a set of data, and it took a bit of effort to cleanse the data, so it looks the way you want it?

The world of data processing and data exchanged between servers and organisations needs careful attention, one person’s idea of clean data might not be other persons, hence the difference between the two can lead to data issues.

Experian had an excellent article What is data cleansing? in that they talk about several factors about data:

  • It could be incorrect
  • and incomplete
  •  and Duplicated

 

One of the things they highlighted also is that under GDPR, organisations have to deal with more focus on data been accurate, complete and up to date.

We are putting together several videos in this area over time, so you will start to see them as they go up.

Please like and share through the social media buttons shared on the page here, thanks for watching!

Data Analytics Ireland

 

 

 

Python Tutorial: How to sort lists

Estimated reading time: 2 minutes

Following on from our post on how to use Python lists have you ever wondered how to sort lists for your Python project?

Our latest video on lists will go through some of the techniques available so that you can get an idea of how to structure your data and sort.

Getting to understand how to implement

In this latest video we will look at:

  • sort() method
  • sorted() function
  • sorting a list through a function

 

Adding in those extra bits to help make the process smoother

Have you thought about sorting ascending/descending?

  • There is also a discussion on this topic as well, and while an index is available for the list, which you may feel does not merit sorting, there could be other logical reasons to implement sorting.
  • Leaving out the reverse = True/False in the sorted method can have an impact, though if you require it left out of the list you have created, automatic ascending will be the default.

On this channel, we have discussed a number of different ways to manage your data. In thinking about sorting a list, why would you want to do this?

Some common reasons are:

  • To visually see if there are duplicates, either on the screen or printed out.
  • If other objects are dependant on the list, say a combo box, then having duplicates visible can help to reduce the size of their contents.
  • Iteration – If you are looking to iterate over a list, it will be quicker if it is sorted.

If you want to learn about lists, using them, and how how they can be iterated over, why not visit Data Analytics Ireland YouTube channel, there are lots of videos there that will help explain the concepts discussed here further.

To get some more links on this topic click here python sort method, it is a blog posting from our website that has some useful links and explanations for you.

YouTube channel lists – Python Lists

Estimated reading time: 2 minutes

Python lists are used extensively in projects, as a result it is important to understand their structure.

Some of the things they can be used for:

  1. Lookup values for comparisons.
  2. Passing data to them to store to be referenced elsewhere.
  3. As part of a loop, store values that have been found through the loop logic.

With methods are associated with lists?

  1. Append – Add values to the end of the list
  2. Extend – adds values from an iterable object to the end of the list.
  3. Insert – You can insert an item to a certain position in a list.
  4. Remove – Remove the first value in a list that has a value that was asked to be looked for.
  5. Pop – This also removes a value at a certain position and returns, consequently if no position is specified then it removes the last item and returns it.
  6. Clear – Removes all items from the list.
  7. Index – returns the index value of the first item found that was asked to be searched for.
  8. Count – returns the number of times an item that was searched or was found in a list.
  9. Sort – Sorts the items in the list.
  10. Reverse – This reverses the items in the list.
  11. Copy – This makes a copy of the list.

What are the properties of a list?

The data type has the following attributes, that make it really useful for a vast array of scenarios:

  • They are ordered – Whatever order the list is a unique characteristic of the list, furthermore changing the order makes it a different list.
  • You can use their index to access the value.
  • They are mutable, meaning you can apply any of the above methods on them.
  • They can contain strings, integers etc, accordingly, there is no restriction on what can be in the list.

Check out the below video playlist from our YouTube channel, they will help explain more about lists:

On this website you can also read about how to compare two lists in Python or how to sort lists using rstudio in addition to this blog post.

We hope you enjoy it!

Data Analytics Ireland