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]
>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.