1

I'm trying to remove duplicates in a list with iteration and slicing (without .remove or fromkeys etc) and keep having wrong result.

For example now I have a list ['a', 'n', 'a', 'a', 'n'] and by running the following code I keep getting ['a', 'a', 'n']

for i in range(1, len(lst)-1):
  if lst[i] == lst[0]:
    lst = lst[1:]
return lst

I think this is the cause: when there are three elements in the list the range becomes range(1, 2) which contains nothing. But even when I change it to

for i in range(len(lst)-1)

which in my opinion makes no sense and should just remove all the elements leaving only the last one ['n'], it still returns ['a', 'a', 'n']

Does anyone know the explanation to this? Why does it seem stuck in this step?

tripleee
  • 175,061
  • 34
  • 275
  • 318
eocolocoo
  • 21
  • 2

1 Answers1

3

You could just put the new elements into a new list like,

>>> x
['a', 'n', 'a', 'a', 'n']
>>> y = []
>>> 
>>> for e in x:
...   if e not in y:
...     y.append(e)
... 
>>> y
['a', 'n']

or just,

>>> list(set(x))
['n', 'a']
han solo
  • 6,390
  • 1
  • 15
  • 19