Using “or” in a python for loop to define default sequence

前端 未结 2 2018
闹比i
闹比i 2021-01-26 20:35

I have seen somewhere this usage of a for loop:

def func(seq=None):
    for i in seq or [1, 2, 3]:
       print i

func([3, 4, 5])  # Will print 3, 4, 5
func()           


        
相关标签:
2条回答
  • 2021-01-26 21:04

    In case of or (or and ) operator, when you do -

    a or b
    

    It returns a if a is not a false-like value, otherwise it returns b . None (and empty lists) are false like value.

    From documentation -

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

    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.

    (Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)


    Also, in case of for loop, in is actually part of the for loop construct, its not an operator. Documentation for for loop construct here.


    Hence when you do -

    for i in seq or [1, 2, 3]:
    

    It would first evaluate -

    seq or [1 , 2, 3]
    

    And returns the seq list if its not none or empty, so that you can iterate over that. Otherwise, it would return [1, 2, 3] and you would iterate over that.

    0 讨论(0)
  • 2021-01-26 21:06

    No! It's the operator priority! or before in
    Precedence, §6.15.
    So seq or [1, 2, 3] is evaluated before entering the loop. And seq is None.

    0 讨论(0)
提交回复
热议问题