-2
my_list = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]

my_list.sort()
print(my_list)
            
list2 = []    


for i in my_list:
    if my_list[i] not in list2:
        list2.append(my_list[i])
        print(list2)
list2.sort()

my_list = list2[:]
            

    
print("The list with unique elements only:")
print(my_list)

The code outputs 1,2,4 and then 9 from the new list in that order (missing the 6) any ideas what's going wrong here?

zjbrown
  • 21
  • 6

1 Answers1

1

Either you go with

for i in my_list:
    if i not in list2:
        ....

or:

for i range(len(my_list):
    if my_list[i] not in list2: 
        .....

you mixed it up. the first way is recommended in python. the weird result is because your i are numbers in the list, which you use as index (by mistake)

Rabinzel
  • 7,757
  • 3
  • 10
  • 30
  • More recommended is to use a descriptive variable name: `for idx in range(...)` or `for item in iterable`. – ddejohn Apr 25 '22 at 19:16
  • true, i thought about changing that too, but then for comparison and making my point, stayed with `i` – Rabinzel Apr 25 '22 at 19:34