1

I'm trying to remove a duplicate element from a list, it is not able to remove it ("1"), can somebody explain what I'm doing wrong

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
    for i in lst:
        print(i)
        if i==1:
           lst.remove(i)

expected output -

[2,3,4,5,6,7,2]

actual output -

[2,3,4,5,6,7,1,2]
bharatk
  • 4,202
  • 5
  • 16
  • 30
Anonamous
  • 253
  • 2
  • 3
  • 14
  • 5
    **Don't remove elements while iterating over it** – Abdul Niyas P M Jul 18 '19 at 13:09
  • 1
    use `sets` to remove duplicates. So `list(set(lst))` will return only unique elements in `lst` – Buckeye14Guy Jul 18 '19 at 13:09
  • 1
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Georgy Jul 18 '19 at 13:10
  • Also, see: [Removing duplicates in lists](https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists/7961390) – Georgy Jul 18 '19 at 13:11
  • 1
    Just noticed that the title and the code are not related at all. See the duplicate target, it answers your question. – Georgy Jul 18 '19 at 13:16

1 Answers1

0

Using list comprehension:

Ex.

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
new_list = [x for x in lst if x != 1]
print(new_list)

O/P:

[2, 3, 4, 5, 6, 7, 2]

OR

Remove all duplicate element from list, use set

Ex.

lst=[1,2,3,4,1,1,1,5,6,7,1,2]
print(list(set(lst)))

O/P:

[1, 2, 3, 4, 5, 6, 7]
bharatk
  • 4,202
  • 5
  • 16
  • 30