![]() |
|
[Tut] Python AND Operator On Two Objects or Lists [What’s The Result?] - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python AND Operator On Two Objects or Lists [What’s The Result?] (/thread-93641.html) |
[Tut] Python AND Operator On Two Objects or Lists [What’s The Result?] - xSicKxBot - 02-17-2020 Python AND Operator On Two Objects or Lists [What’s The Result?] You may already know Python’s and operator when applied to two Booleans: Code: >>> True and False
False
>>> True and True
TrueSimple enough. Yet, that’s not the whole story: you can use the Code: andWhat If You Apply the AND Operator To Two Objects? To understand the output, you have to understand two things:
Let’s answer those two questions quickly. How does the Code: andLet’s start with the official documentation for Boolean operators: Operation | Definitions Code: x or yif x is false, then y, else x Code: x and yif x is false, then x, else y Code: not xif x is false, then Code: TrueCode: FalseYou must understand the deeper meaning of those definitions: all of them are short-circuit which means that as soon as the condition is fullfilled, they will abort further processing. In the Code: x and yCode: xCode: TrueCode: yCode: yCode: xCode: yCode: xCode: TrueCode: yCode: xCode: yCode: TrueThis leads to the interesting behavior: if Code: xCode: yCode: x and yIn combination with the next piece of Python knowledge, this leads to an interesting behavior: What’s the truth value of any object – such as a list? The Python convention is simple: if the object is “empty”, the truth value is Code: FalseCode: TrueCode: FalseCode: TrueNow, you’re equipped with the basics to understand the answer to the following question: What If You Apply the AND Operator To Two Objects? Say, you’ve got two non-Boolean objects Code: xCode: yCode: x and yThe answer is simple: the result is Code: yCode: xCode: TrueWhat If You Apply the AND Operator To Two Lists? Here’s an example for two list objects: Code: >>> [1, 2, 3] and [0, 0, 0, 0]
[0, 0, 0, 0]The first argument of the Code: andCode: TrueCode: [0, 0, 0, 0]But what if the first argument is empty? Code: >>> [] and [0, 0, 0, 0]
[]The result is the first argument (and not a Boolean value Code: FalseCode: x and ySummary You’ve learned that the Code: andCode: FalseYou’ve also learned that you can use the Code: andFinally, you’ve also learned that an empty object usually evaluates to Code: FalseIf you find this interesting, feel free to check out my upcoming Python book that shows you hundreds of small Python tricks like this one: ![]() Python One-Liners [No Starch Press] Get your book! |