0
biology = ["Sarah", "Ahmed", "Fred", "Gillian", "Shradah", "Max", "Max", "Sara", "Max", "Esther"]

computerScience = ["Sarah", "John", "Fred", "Gillian", "Jermaine", "Max", "Sara", "Juan", "Esther"]

english = ["Nico", "Sharjeel", "Isabella", "Taylor", "Ali", "Ali", "Jean-Baptiste", "Jean-Baptiste", "Jean-Baptiste", "William"]


setThing=set()
for word in biology:
  setThing.add(word)

listThing=[]

for word in setThing:
  listThing.append(word)

print(listThing)

In this, I am trying to take the list called biology and put it in a set so that it gets rid of the repeats. I am trying to turn it back into a list that has the same order of names as the list: biology. But when I turned it into a set, the order of the names completely changed. Is there any way I could use some kind of function to order either the new set or the new list so that the names are in the same order as the original "biology" list?

  • sets are not ordered, unlike dicts: https://stackoverflow.com/questions/45581901/are-sets-ordered-like-dicts-in-python3-6 – Lesiak Oct 07 '20 at 13:49
  • have a look at `unique_everseen` in the [itertools recipes](https://docs.python.org/3/library/itertools.html?highlight=unique_everseen#itertools-recipes). – hiro protagonist Oct 07 '20 at 13:50
  • You can use: `[lst[i] for i in set([lst.index(i) for i in lst])]` - where `lst` is `biology`. This basically creates a list of indexes and populates the new list based on the item's index in the old list. – S3DEV Oct 07 '20 at 14:08

1 Answers1

0

Use

biology  = list(dict.fromkeys(biology))

This will remove duplicates in order and return the unique elements in a list

abdulsaboor
  • 678
  • 5
  • 10