This content originally appeared on CodeSource.io and was authored by Deven
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']
The post How to solve indexerror: list assignment index out of range appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Deven

Deven | Sciencx (2021-03-16T04:34:28+00:00) How to solve indexerror: list assignment index out of range. Retrieved from https://www.scien.cx/2021/03/16/how-to-solve-indexerror-list-assignment-index-out-of-range/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.