-4

I'm trying to set the second appearance of a text in a list to 0. The first appearance of the word should remain untouched.

e.g.

Xlist=["dog", "cat", "horse", "dog"]

The outcome should look like this:

["dog", "cat", "horse", "0"]

Is there a simple way to do it? Since I'm new to python programming I can't really imagine how to do it and I didn't find a way in other threads.

kederrac
  • 16,819
  • 6
  • 32
  • 55
  • Find [indices of dupes](https://stackoverflow.com/q/5419204/4636715) and set the values of those indices to `0` (except the first item which you want to keep in your case) – vahdet Feb 11 '20 at 09:37
  • What about third appearance of an element? Should only 2nd appearance be set to 0? – Ch3steR Feb 11 '20 at 09:43
  • This problem is not very well defined. What should happen to this list: `["dog", "cat", "dog", "dog", "cat", "horse"]`? – Błotosmętek Feb 11 '20 at 09:45
  • Looks like an exercise. Please provide what you have tried, why it isn't working, etc. [Help-Center: how-to-ask](https://stackoverflow.com/help/how-to-ask) – Dorian Turba Feb 11 '20 at 09:47
  • The answer @jaswanth has provided already solved my problem. Every appearance after the 2nd should be changed to "0". Sorry if that was misleading – JulianWe994 Feb 12 '20 at 08:31

1 Answers1

1
keys = set([])
for index, item in enumerate(data):
    if item in keys:
        data[index] = "0"
        continue
    keys.add(item)

print(data)   

I hope this works for you

jaswanth
  • 515
  • 2
  • 7
  • 3
    I would recommend to use `set` data type for `keys` instead of a `list`. – Ch3steR Feb 11 '20 at 09:42
  • Thanks, for people who did not understand It is better because the time complexity of searching in a set is less compared to a list that is why it is better to use `set` instead of `list`. edited the solution – jaswanth Feb 11 '20 at 09:55