0

Don't understand a part of this code (Python)

I have the following code: items = ["Blue", "Red", "Black"] def myFunc(item): seen = list() return not any(i in seen or seen.append(i) for i in item) print(myFunc(items)) (https://code.sololearn.com/cuO35hGAhWCu) It prints "True" if all the items in the items list are unique, if there are one or more items in the list that occur more than one time, then it prints "False". I don't, however, understand the return part of the code (line 5), can someone please explain it?

17th Sep 2021, 6:50 PM
Ethan
Ethan - avatar
4 Respuestas
+ 2
Let's start with the generator: i in seen or seen.append(I) for i in item That generator will create another list that we are going to refer as the "generator list". What that generator does is: - we are going to loop every item on your evaluated list (for i in item) - for each item in you list we are going to see is that item is contained in another list "seen" * if that item is in seen, then append to the generator list True (i in seen) * If that item is not in seen, it will append to seen the value of the item (or seen.append(i)) So if a item is repeated inside your list, the first time the generator read that value, will append it to seen. The second time it reads the same value, it will append to the generator list True. The "any" function will evaluate if inside the generator list is at least one True value, which will happen only when your list has repeated items. And "not" will reverse that boolean (True when they're no repeated values).
17th Sep 2021, 11:03 PM
TheBigOne
TheBigOne - avatar
+ 4
1) any returns True if any "i in seen" in that generator return True for a item. And it will only return True if item is repeated . 2) any will return False if none of the "i in seen" Returns true for a item which means item is not repeated. Now if any returns True then "not True" will be equal to False and vice versa.
17th Sep 2021, 7:34 PM
Abhay
Abhay - avatar
+ 1
It looks for any item in the list, one by one, to see if there is any of them that is duplicated. The answer is False but because of the "not" the answer is converted to True.
17th Sep 2021, 8:19 PM
Raoul Živolić
Raoul Živolić - avatar
0
@Abhay I understand that but why is there a for loop at the end of the any() function? Is it just the syntax for the any() function?
23rd Sep 2021, 4:33 PM
Ethan
Ethan - avatar