-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.

5
  • Find indices of dupes and set the values of those indices to 0 (except the first item which you want to keep in your case) Commented Feb 11, 2020 at 9:37
  • What about third appearance of an element? Should only 2nd appearance be set to 0? Commented Feb 11, 2020 at 9:43
  • This problem is not very well defined. What should happen to this list: ["dog", "cat", "dog", "dog", "cat", "horse"]? Commented Feb 11, 2020 at 9:45
  • Looks like an exercise. Please provide what you have tried, why it isn't working, etc. Help-Center: how-to-ask Commented Feb 11, 2020 at 9: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 Commented Feb 12, 2020 at 8:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would recommend to use set data type for keys instead of a list.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.