-2

Basically, I have a list with the following words

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country'] 

(this was the example given to me by my teacher and it is pretty good for testing).

I want to figure out how to remove any duplicates and print out the new list without said duplicates, so the output should be

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you'] 

After initially trying to use the set(), I managed to remove the duplicates, but it just prints out the sentence in a random order, which is quite bothersome.

Here is my code:

sentence = input('Please enter a sentence. No punctuation may be included: enter code here').lower().split()
print('This is your sentence:', sentence)
no_duplicates = list(set(sentence))
print('This is your sentence without duplicates', no_duplicates)

By the way, incase you didn't notice, I'm still quite a newb to coding so try and keep your answers simple so that I may understand what you're saying.

gtlambert
  • 11,711
  • 2
  • 30
  • 48
Bruno
  • 1
  • 2

2 Answers2

0

Sets are not random, but they are unordered. This means that you can't use them just like this in your use case, because order is important in this task.

However, there is a simple solution using sets. Since this is homework, I won't give you the code, but the algorithm is to start with an empty set, then iterate through each word, checking if it is already in the set: if it isn't, add it to the set and to the output list, otherwise skip it.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Why not use an OrderedDict

>>> lst=['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country']
>>> from collections import OrderedDict
>>> [k for k in OrderedDict((el,0) for el in lst)]
['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
Pynchia
  • 10,996
  • 5
  • 34
  • 43