Deleting Repeats In A List Python
Possible Duplicates:
How do you remove duplicates from a list in Python whilst preserving order?
In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?
I was wondering if there was a function which does the following:
Take a list as an argument:
list = [ 3 , 5 , 6 , 4 , 6 , 2 , 7 , 6 , 5 , 3 ]
and deletes all the repeats in the list to obtain:
list = [ 3 , 5 , 6 , 4 , 2 , 7 ]
I know you can convert it into a dictionary and use the fact that dictionaries cannot have repeats but I was wondering if there was a better way of doing it.
Thanks
Answer
Please see the Python documentation for three ways to accomplish this. The following is copied from that site. Replace the example 'mylist' with your variable name ('list').
First Example: If you don’t mind reordering the list, sort it and then scan from the end of the list, deleting duplicates as you go:
if mylist:
mylist.sort()
last = mylist[-1]
for i in range(len(mylist)-2, -1, -1):
if last == mylist[i]:
del mylist[i]
else:
last = mylist[i]
Second Example: If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster:
d = {}
for x in mylist:
d[x] = 1
mylist = list(d.keys())
Third Example: In Python 2.5 and later:
mylist = list(set(mylist))
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module