Reputation: 1
Without importing another function check if a list contains two of the same element
F.E list = [3,4,5,3] since 3 appears twice in the list return True
Thanks for the help
Upvotes: 0
Views: 13048
Reputation:
There are different approaches to solve this problem.
Solution 1: Use set()
if len(set(<your_list>))<len(<your_list>):
return False
else:
return True
Solution 2 : Use hash dictionary
def check_list(lst):
hash_dict={}
for elem in lst:
if elem not in hash_dict:
hash_dict[elem]=1
else:
return True
return False
In the above solution, we add the elements in the hash dict and constantly check if it exists there, if it does then we return True. If the list has no duplicate or more than 2 elements then it will just return false.
Solution 3 : We can also use counter from collections
from collections import Counter
new_dict=Counter(<your list>)
return True if 2 in new_dict.values() else False
Upvotes: 0
Reputation: 150
If you need to check if the element occurs exactly twice, you could do this:
l = [3,4,5,3]
if 2 in set([l.count(n) for n in l]):
print('True')
Upvotes: 2
Reputation: 36329
You can convert to set
and check the resulting length:
len(set(data)) < len(data)
Upvotes: 3