error solved

How to solve indexerror: list assignment index out of range


In this article, you will learn how to solve indexerror: list assignment index out of range Python error.

Let’s look at a code example that produces the same error.

fruits = ["mango", "apple", "banana"]
apple = []
for c in range(0, len(fruits)):
	if "apple" in fruits[c]:
		apple[c] = fruits[c]

print(fruits)

Output

Traceback (most recent call last):
  File "<string>", line 5, in <module>
IndexError: list assignment index out of range

In order to solve indexerror: list assignment index out of range Python error you need to  use append() to add an item to a list. consider the code example below:

fruits = ["mango", "apple", "banana"]
apple = []
for c in range(0, len(fruits)):
	if "apple" in fruits[c]:
		apple.append(fruits[c])

print(fruits)

Output

['mango', 'apple', 'banana']

Share on social media

//