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()
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 evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
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 expressions 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.
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
.