EDIT: there are great answers. Adding some simpler ways to achieve the wanted result:
Method 1:
items = ["Blue", "Black", "Red"]
items_set = set(items)
if len(items_set) != len(items):
# there are duplications
This works because a set object ‘removes’ duplications.
Method 2:
contains_duplicates = any(items.count(element) > 1 for element in items) # true if contains duplications and false otherwise.
See https://www.kite.com/python/answers/how-to-check-for-duplicates-in-a-list-in-python
———————————————
any
is a great function
Return True if any element of the iterable is true. If the iterable is empty, return False
Your function isUnique
, however, does a bit more logic. Let's break it down:
First you create an empty list object and store it in 'seen' variable.
for i in item
- iterates the list of items.
i in seen
- This statement returns True if 'i' is a member of 'seen', and false otherwise.
seen.append(i)
- add i to seen. This statement returns None if 'i' is appeneded to seen successfully.
Notice the or
statement between i in seen or seen.append(i)
. That means, if one of the statements here is True, the or statement returns True.
At this point, I'd run [i in seen or seen.append(i) for i in item]
, see the result and experiment with it. The result for your example is [None, None, None]
.
Basically, for each item, you both add it to the list and check if it is already in the list.
Finally, you use the any()
function - which returns True if the iterable has a True
value. This will happen only if i in seen
will return True.
Notice you are using not any(...)
, which returns False in case there are no repititions.
There are simpler and clearer ways to implement this. You should try!