Python

How to Fix list assignment index out of range

While working with Lists in Python, you may have a requirement to insert or update the elements in a List based on the index position. Without knowing the size (total number of elements in a List), when you try to insert or update the element based on an index that does not exist in the List, IndexError: list assignment index out of range is raised. In this guide, we will discuss how to fix this error by providing five different solutions with examples.

Reproducing the Error

First, we will reproduce the error and then fix it. Create a List of five industries and try to insert a new industry, ‘Agriculture,’ with an index that doesn’t exist in the List.

# Create List of industries

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data)

# Try to modify 6th element to "Agriculture"

data[5]='Agriculture'

Output

You can see that data, List, holds five elements. The index positions will be from 0 to 4. Here, when we try to update the index 5, that doesn’t exist, an error is raised.

Solution 1: Knowing Length

Before updating or inserting an element, we should know the length of the List using the len() function. Based on this, we can update the existing index elements.

Example 1: Modify the Last Element

Utilize the same List (data) and use the len() function to modify the last element to ‘Agriculture.’

Pass the index as [len(List) – 1]. This will provide the last index position of the List.

# Create List of industries
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
print("Industries: ",data)
print("Total number of Industries: ",len(data),"\n")

# Modify the last element to "Agriculture"
data[len(data)-1]='Agriculture'
print("Industries: ",data)

Output

The total number of elements in the above List is five. Therefore, the index is 5-1, which equals 4. The element present at the 4th index is updated to “Agriculture.”

Example 2: Modify the First Element

Utilize the same List (data) and use the len() function to modify the first element to ‘Agriculture.’

Pass the index as [len(List) – len(List)]. This will provide the first index position, which is 0.

# Create List of industries
data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
print("Industries: ",data)
print("Total number of Industries: ",len(data),"\n")

# Modify the first element to "Agriculture"
data[len(data) - len(data)]='Agriculture'
print("Industries: ",data)

Output

The total number of elements in the above List is five. Therefore the index is 5-5, which equals 0. The element present at the 0th index is updated to “Agriculture.”

Solution 2: Using append()

In a List, append() method is used to insert an element at the end of the List. It takes only the element as a parameter and appends it to the List.

Example

Insert the element “Agriculture” at the end of the list using the append() method.

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']
print("Industries: ",data,"\n")

# Add "Agriculture" at the end of the list

# using append()
data.append('Agriculture')
print("Industries: ",data,"\n")

Output

‘Agriculture’ is added to the List without any Error.

Solution 3: Using insert()

In List, insert() method is used to insert the element at a specific position. It takes the position (Index) as the first parameter and the element to be inserted as the second parameter. We can use this function to insert the element at the first, last, or specified position such that IndexError will not occur.

Syntax

  1. Inserting at the last position – list.insert(len(list), element)
  2. Inserting at the first position – list.insert(0, element)

Example 1: Inserting at the Last Position

Insert the element “Agriculture” at the end of the list using the insert() function.

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data,"\n")

# Add "Agriculture" at the end of the list

# using insert()
data.insert(len(data), "Agriculture")
print("Industries: ",data,"\n")

Output

‘Agriculture’ is added at the end of the List without any Error.

Example 2: Inserting at the First Position

Insert the element “Agriculture” at the beginning of the list using the insert() function.

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data,"\n")

# Add "Agriculture" at the first of list

# using insert()
data.insert(0, "Agriculture")
print("Industries: ",data)

Output

‘Agriculture’ is added at the beginning of the List without any error.

Example 3: Inserting at the Specific Position

Add “Agriculture” at the fourth position (Index = 3) of the list using the insert() function.

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data,"\n")

# Add "Agriculture" at the specific position

# using insert()
data.insert(3, "Agriculture")
print("Industries: ",data,"\n")

Output

‘Agriculture’ is added at the 3rd index position of the List without any Error.

Solution 4: Handling Error

One of the best ways is to handle the errors by specifying the try-except blocks. It is a good approach to specify the code inside the try block so that the code is handled in the except block. So in our case, we need to specify the IndexError in the except block. If the index does not exist, then the Custom Error Message is displayed instead of the actual error. This will not affect the other statements in the script.

Syntax

try:

statements…

except IndexError:

Error messages…

Example 1

Try to modify the 6th element to “Agriculture.” Create the except block that handles the IndexError and specify the message as ‘Assignment Index does not exist’ within the print statement inside this block.

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data,"\n")

# Try to modify 6th element to "Agriculture"
try:
data[5] = 'Agriculture'
except IndexError:
print('Assignment Index does not exist')

Output

Index – 5 does not exist in the List.

Example 2

Modify the 4th element (Index = 3) to “Agriculture.”

data = ['Insurance','Machinery','Manufacturing','Media','Not For Profit']

print("Industries: ",data,"\n")

# Modify 4th element to "Agriculture"
try:
  data[3] = 'Agriculture'
  print("Industries: ",data)
  except IndexError:
  print('Assignment Index does not exist')

Output

Index – 3 exists in the List. “Agriculture” replaces the “Media.” In this case, the except block is not executed since the index exists in the List.

Solution 5: Declare List with Empty Elements and Update Index

The last approach is to create a list dynamically with a specific size with None values or empty strings. After that, we can modify the elements at a specific index.

Example

Let’s create List with 10 (Taken input from the user) empty strings and

  1. Update the 6th element (Index = 5) to ‘Agriculture’.
  2. Update the 1st element (Index = 0) to ‘Banking’.
  3. Update the 3rd element (Index = 2) to ‘Media’
n=int(input("How many elements you want in List: ?"))

data = [' '] * n

print(data,"\n")

# Update 6th element to 'Agriculture'
data[5] = 'Agriculture'

# Update 1st element to 'Banking'
data[0] = 'Banking'

# Update 3rd element to 'Media'
data[2] = 'Media'
print(data)

Output

First, the List holds ten empty strings. After that, we added three elements at different existing index positions.

Conclusion

In order to fix the error, you need to know the length of the List before inserting an element at a specific index position. Then, we utilized the append() method and insert() function to insert the element. Later, we handle the error by specifying the try-catch block. Finally, we discuss how to create a dynamic list with empty strings and update the elements based on the existing index positions.

About the author

Gottumukkala Sravan Kumar

B tech-hon's in Information Technology; Known programming languages - Python, R , PHP MySQL; Published 500+ articles on computer science domain