1

Why am i getting this error when trying to remove dupes from a list?

"TypeError: 'int' object is not subscriptable"

trying to remove duplicate valuse from a list

numbers=[5,2,1,7,2,4]
numbers.sort()
i=0
for item in numbers:
    if i==len(numbers)-1:
    break
    elif item[i]==item[i+1]:
    numbers.remove(item)
i+=1

3 Answers 3

1

Actually the problem is in your for loop it is not for removing duplicate numbers. i recommend that you must define a empty list in which you append elements one by one using loop and check if the element is already present in your list then don't append. here is the code:

numbers=[5,2,1,7,2,4]
numbers.sort()
sorted_num=[]
i=0
for i in range(0,len(numbers)-1):
    if numbers[i] in sorted_num:
        continue
    else:
        sorted_num.append(numbers[i])
        i+=1
print (sorted_num)
#     elif item[i]==item[i+1]:
#         numbers.remove(item)
# i+=1

i only edited your piece of code

Sign up to request clarification or add additional context in comments.

1 Comment

interesting approach. Thank you
0

use set see more here


numbers=[5,2,1,7,2,4]   

list(set(numbers))      
[1, 2, 4, 5, 7]


1 Comment

My problem was from a homework and i don`t think i can use "set". But it is good to know this command exists. thank you.
0

Use dictionary:

numbers=[5,2,1,7,2,4,5,5,1]
numbers=list(dict.fromkeys(numbers))
print(numbers)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.