How to remove all the duplicate items in a list?

Here is a code:

shopping_line = [“Cole”, “Kip”, “Chris”, “Sylvana”, “Chris”]

now, i would like to remove 2 Chris from the list. How do i do that?

shopping_line.remove(“Chris”)
print(shopping_line)

[“Cole”, “Kip”, “Sylvana”, “Chris”]

But this will remove only the first one. :thinking:

To get the unique elements from a list in python you can use the built in set() function:

lst = [1, 2, 1, 3, 4, 3, 4, 5, 5]
print(list(set(lst)))
[1, 2, 3, 4, 5]

Though note that set() does not return a list but a “set” object, for most purposes you will need to convert it to a list in order to work with it, as done above.

EDIT:

It may be important to note that set() does not guarantee order of elements so set() may not be the way to go. In this event you could use a looping method. Say you have a function that takes a lst as input, and creates an empty list to hold the result. Then loop through the input and for every value check if it is in the result list, if it is not .append() it. Finally return the result.

Spoiler alert
def unique(lst):
  result = []
  for i in lst:
    if i not in result:
      result.append(i)
  return result

print(unique(lst))
2 Likes