Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my code giving a value error that the list index is out of range?

inp_list=[10,1,11,1,29,876,768,10,11,1,92,29,876]

for i in range(len(inp_list)):
    for j in range(i+1, len(inp_list)):
        if (inp_list[i]==inp_list[j]):
            inp_list.remove(inp_list[i])
            
print(inp_list)

In the code, I was trying to remove the duplicate elements in the list. It is giving me a ValueError for line if (inp_list[i]==inp_list[j):, I am not able to understand why is it showing me an error.

I tried looping through the elements of the list using its index numbers in the first for loop. In the second for loop, I was trying to loop through the elements with index numbers index+1, but I limited the end value of the range within the the length of the list. Still, I am getting a ValueError, saying that the list index is out of range.

I expected the output to be like this:
[10,1,11,29,876,768,92]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you’re removing elements from inp_list, which means it gets shorter, but the ranges you’re looping through still have the indexes for the old size of the list. So you end up going past the end of the now-shorter list.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading