0

I was solving a coding problem on Codefights and I ALMOST solved it but, a problem in my code occured and I can't find a way to solve the problem.

my_list = [1, 2, 3, 4, 3, 6]
print(my_list.index(3))

Output : 2

print(my_list[4])

Output : 3 But, here's the problem, when I try to remove the 3 which lies on index 4, Python removes the 3 on the 2nd index, and I don't want this to happen. For example:

my_list.remove(my_list[4])
print(my_list)

Output : [1, 2, 4, 3, 6] I want to get the output as : [1, 2, 3, 4, 6]

This is not my actual code, but just an example. Please help me out if you can.

Zunayn
  • 132
  • 8
  • 2
    Convert into a set, all duplicate values are removed. my_set=set(my_list) – Amol Manthalkar Dec 17 '17 at 06:57
  • 2
    Possible duplicate of [Difference between del, remove and pop on lists](https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists) – Aaditya Ura Dec 17 '17 at 07:01

1 Answers1

1

This is actually the expected output. You should use del instead.

del my_list[4]

The reason it was not working is that using this line:

my_list.remove(my_list[4])

translates in this line:

my_list.remove(3)

since my_list[4] return 3, which will then delete first occurence of 3 in the list.

scharette
  • 9,437
  • 8
  • 33
  • 67