I have a script that checks if there are one or more of the same items in a list. Here's the code:
items = ["Blue", "Black", "Red"]
def isUnique(item):
seen = list()
return not any(i in seen or seen.append(i) for i in item)
print(isUnique(items))
It prints "True" if all the items in the given list are unique and "False" if one or more items in the list are unique. Can someone please explain the any()
part of the script for me as I don't fully understand how it works?
This code is kind of a hack, since it uses a generator expression with side-effects and exploits the fact that append
returns None
, which is falsy.
The equivalent code written in the imperative style is like so:
def isUnique(items):
seen = list()
for i in items:
if i in seen or seen.append(i):
return False
return True
The or
is still a bit strange there - it is being used for its short-circuiting behaviour, so that append
is only called when i in seen
is false - so we could rewrite it like this:
def isUnique(items):
seen = list()
for i in items:
if i in seen:
return False
else:
seen.append(i)
return True
This is equivalent because append
is only called when i in seen
is false, and the call to append
returns None
which means the return False
line shouldn't execute in that case.