简体   繁体   中英

Or keyword inside a print statement in Python?

How does Python decide the output of this ?

print([1, 2] or ["hello"])

I mean why will always print([2] or ["az"]) output [2] and not ["az"] ?

由于这些列表包含元素,因此它们将求值为True因此Python会打印以True字面量为先的那一个。

There are two things you have to understand here. First:

x or y

If x is truthy, it has the value of x (without even evaluating y , so 23 or launch_nukes() doesn't launch the nukes).

Otherwise, it has the value of y .

Or, as the docs put it:

The expression x or y first evaluates x ; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Notice that it uses the word "true" here, not the value True . This is a bit confusing (even more so if you're talking out loud, or typing in ASCII without formatting…), which is why everyone says "truthy".


So, what do "truthy" and "falsey" mean? 1

  • "x is truthy" does not mean x == True , it means bool(x) == True .
  • "x is falsey" does not mean x == False , it means bool(x) == False .

For all builtin and stdlib types:

  • False is falsey.
  • None is falsey.
  • Numeric zero values are falsey.
  • Empty containers are falsey.
  • Everything else is truthy.

Notice that None and empty containers are falsey, but they're not equal to False .

By convention, third-party types (including types that you define 2 ) should follow the same rules. But sometimes there are good reasons not to. (For example, a NumPy array is neither truthy nor falsey. 3 )

This is covered loosely in the same docs section :

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

The exact details for all builtin types are buried in the standard type hierarchy , which is where you learn things like whether bytes is covered by "strings and containers" (yes) or whether there's anything special about NotImplemented (nope, it's truthy).


So, let's go through your examples:

[1, 2] or ["hello"]

Since [1, 2] is a non-empty container, it's truthy. So this equals [1, 2] .

[] or ["hello"]

Since [] is an empty container, it's falsey. So this equals ["hello"] .

[] == False

[] may be falsey, but it's not False , or even equal to False . Only numbers equal other numbers, and False is the number 0 in the numeric type bool , 4 but [] is not a number. So this is False .


Just be glad you didn't ask about is . :)


1. Technically, these terms aren't defined, even though everyone, even the core devs, uses them all the time. The official reference defines things in terms of evaluating to true or false as a boolean, and then explains what that means elsewhere.

2. You can control whether your types' values are truthy by defining a __bool__ method—or by defining __len__ . The only things you're allowed to do are return True , return False , or raise an exception; if you try to return anything different, it raises a TypeError . So, everything is either truthy, or falsey, or untestable.

3. If you try to check its truthiness, it will raise an exception. That's because NumPy uses boolean arrays widely—eg, array([1, 2]) < array([2, 1]) is array([True, False]) , and you don't want people writing if array([1, 2]) < array([2, 1]): , since whatever they're expecting it to do probably doesn't make sense.

4. Yes, bool is a numeric type—in fact, a subclass of int . This is a little weird when you're first learning, but it turns out to be useful more often than it's dangerous, so it's not just preserved for historic reasons.

x or y [or z or z1 or z2 or ...] returns the first Truthy element in sequence, or the last Falsey element if all are Falsey.

x and y [and z and z1 and z2 and ...] returns the first Falsey element in sequence, or the last Truthy element if all are Truthy.


Python has a notion of Truthiness and Falsiness that is separate from True and False . An empty list is not False , but it is Falsey . bool(something_truthy) == True and bool(something_falsey) == False .

Most things are Truthy, so it's easier to list the Falsey things:

  • 0 (note that -1 is Truthy)
  • None
  • Empty collections ( [] , {} , set() , "" , and etc. Note that non-empty collections containing entirely Falsey elements are still truthy eg [None, None, None, None] )
  • False

Everything else is Truthy.


In your example: [1, 2] or ["hello"] == [1, 2] because the first element, [1, 2 is Truthy (the fact that ["hello"] is also Truthy is irrelevant in this case). Note that [1, 2] and ["hello"] == ["hello"] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM