Home >Backend Development >Python Tutorial >How to remove duplicates from a python list?
How to remove duplicates from a python list? The following article will introduce to you how to remove duplicates from a python list. I hope it will be helpful to you. (Recommended learning: python video tutorial)
Python list deduplication method:
1. Use the loop search method
li = [1,2,3,3,4,2,3,4,5,6,1] news_li = [] for i in li: if i not in news_li: news_li.append(i) print (news_li)
Output:
[1, 2, 3, 4, 5, 6]
2. Use the set feature set()
li = [1,4,3,3,4,2,3,4,5,6,1] new_li = list(set(li)) print (new_li)
Output:
[1, 2, 3, 4, 5, 6]
3. Use the grouby method of itertools module
import itertools li = [1,4,3,3,4,2,3,4,5,6,1] li.sort() #排序 it = itertools.groupby(li) for k, g in it: print (k)
Output:
1 2 3 4 5 6
4. Use keys() method
li = [1,0,3,7,7,5] formatli = list({}.fromkeys(li).keys()) print (formatli)
Output:
[1, 0, 3, 7, 5]
For more python related technical knowledge, please visit the python introductory tutorial column to learn!
The above is the detailed content of How to remove duplicates from a python list?. For more information, please follow other related articles on the PHP Chinese website!