What is the most efficient way to:
- Check if a list has duplicate items (return a boolean)
- Get duplicate items in a list (return a list)
I'm looking for something quick and concise, as my solutions are rather cumbersome:
def list_has_duplicate_items( L ):
for item in L:
if L.count(item) > 1:
return True
return False
def get_duplicate_items( L ):
new = set()
for item in L:
if L.count(item) > 1:
new.add( item )
return list(new)
L = [ 'oranges' , 'apples' , 'oranges' , 'grapes' ]
print 'List: ' , L
print 'Does list have duplicate item(s)? ' , list_has_duplicate_items( L )
print 'Redundant item(s) in list: ' , get_duplicate_items( L )
"""Ouput:
List: ['oranges', 'apples', 'oranges', 'grapes']
Does list have duplicate item(s)? True
Duplicate item(s) in list: ['oranges']"""
I'm wondering why there isn't a set function that will pop out the duplicate items. Also, a side question: Am I using return statements in the proper way? Thanks.
Any help greatly appreciated!