-2
myList = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]
for i in myList:
    t=myList[i]
    for j in range(i+1,len(myList)):`
        if myList[j]==t :
            del myList[j]

print("The list with unique elements only:")
print(myList)
Leo Arad
  • 4,452
  • 2
  • 6
  • 17

1 Answers1

2

First of all, you should not delete list elements while iterating over the list. This causes problems because the list would be changing.

And second, you can get the unique elements of list by converting it to set:

myList = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]
uniques = list(set(myList))
Amir
  • 1,885
  • 3
  • 19
  • 36
  • but since i have included len(mylist) as upper limit,shouldn,t it be evaluating everytime and change the upper limit accordingly? – Swapnil Pandey Jun 20 '20 at 10:35
  • no, it does not evaluate every time. As a general rule, it is better to not mutate the data, which means you shouldn't **change** your data, but instead you should **create** a new data based on your old one. For example in this code, the `uniques` list is a totally separate object and has no connection or relation to `myList`. – Amir Jun 20 '20 at 10:56