Skip to content Skip to sidebar Skip to footer

Using "or" In A Python For Loop To Define Default Sequence

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() # Will pri

Solution 1:

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.

Solution 2:

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

Post a Comment for "Using "or" In A Python For Loop To Define Default Sequence"