0

Python "and" "or" behaviour with lists

I am very confused by the behaviour of the "and" and "or" operators with lists in python. The behaviour with "int" is as expected, "1 and 0" equals 0 and "1 or 0" equals 1. I did some poking around I found out that only an empty list will be false. print([]) # will print false print(["s"]) # will print true But the list behaviour is as follows. a = [0,0,0] b = [1,1,1] c = a and b # c will equal to 1 d = a or b # d will equal to 0 WHY?

27th Jan 2019, 6:02 PM
Vladislav
Vladislav - avatar
2 Antworten
+ 4
c will be [1,1,1] and d will be [0,0,0]. To evaluate 'and', each item has to be checked and only if the last item is True, python knows that the whole expression is True. That's why c is equal to the last list here. 'Or' is True if one or more items are True. The list [0,0,0] is not empty, so it evaluates to True (even though it only contains zeros). The second list doesn't need to be checked because the first one is True. So the first list is returned. By the way, check your examples with other numbers. Following the same logic, "5 and 7" is 7 and "5 or 7" is 5. It looks like you only checked for ones and zeros so you might think that the result is a boolean (0 = False, 1 = True). But that's not the case. "or" returns the first item that evaluates to True. "and" returns the last item if all items are True.
27th Jan 2019, 6:19 PM
Anna
Anna - avatar
+ 1
Ahhhhhh Pointing out that the result is not a boolean, that was crucial Anna. Your explanation is good for reference Echo Echo. Thanks
27th Jan 2019, 7:48 PM
Vladislav
Vladislav - avatar