-1
text = """ sam 
may 
sam 
gray 
bet 
four 
vet 
large """

find = "a"

words = text.split("\n")
for w in words:
  if find in w:
    print(w)
  else :
    pass

What could I add to make this code not print 'sam' (in this case) twice?

  • 1
    Use a set, i.e. `words = set(text.split("\n"))`. The downside is that `set`s are not ordered. – Selcuk Jul 19 '20 at 23:41
  • Do I use this instead of `words = text.split("\n")` – Connor Oflanagan Jul 19 '20 at 23:43
  • 1
    Does this answer your question? [How do you remove duplicates from a list whilst preserving order?](https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order) – Jab Jul 19 '20 at 23:53

1 Answers1

1

Try this:

text = """
sam 
may 
sam 
gray 
bet 
four 
vet 
large """

find = "a"
used = []

words = text.split("\n")
for w in words:
  if find in w and w not in used:
    print(w)
    used.append(w)
  else :
    pass
Raiyan Chowdhury
  • 281
  • 2
  • 20
  • This is a good method to keep the original order of `text`, but it is inefficient as making lookups in a list is `O(n)` while using a set is `O(1)`. You could get a free performance boost by defining `used` as a set. – Selcuk Jul 19 '20 at 23:58