Mr Coolman
Mr Coolman

Reputation: 25

How do I remove duplicated elements from a python array?

What I just want to achieve is to be able to get a list with elemnts that aren't repeating
<current state>
results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]

<expectation>
results=["Anna","Michael", "Juliet"]

Upvotes: 0

Views: 71

Answers (2)

Bert Blommers
Bert Blommers

Reputation: 2123

You can conver the list to a set, which has no duplicates by definition.

results = set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"])

If you need the type of the result to be a list, you can simply convert it back:

results = list(set(["Anna","Michael","Anna","Juliet","Juliet", "Anna"]))

Upvotes: 0

Shawn Wilcox
Shawn Wilcox

Reputation: 36

The following will remove duplicates.

results = ["Anna","Michael","Anna","Juliet","Juliet", "Anna"]
results = list(dict.fromkeys(results))
print(results)

Output:

['Anna', 'Michael', 'Juliet']

See https://www.w3schools.com/python/python_howto_remove_duplicates.asp for more information.

Upvotes: 1

Related Questions