1

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 print 1, 2, 3

It seems that when using or/and when using the "in" keyword it will select the first/last "usable" sequence in order to run the for loop.

I have not seen any official documentation and was wondering how it works and if it's commonly used.

martineau
  • 119,623
  • 25
  • 170
  • 301
Nir
  • 894
  • 3
  • 13
  • 24
  • `seq or [1, 2, 3]` is roughly equivalent to `seq if len(seq) > 0 else [1, 2, 3]`, i.e. providing a default in case it gets an empty sequence. See https://docs.python.org/2/library/stdtypes.html#truth-value-testing – jonrsharpe Jul 26 '15 at 12:32
  • @jonrsharpe it's more like `seq if bool(seq) else [1,2,3]`, with the empty list being `False`! – Karl Barker Jul 26 '15 at 12:33
  • @KarlBarker that's more accurate but probably less helpful! – jonrsharpe Jul 26 '15 at 12:34

2 Answers2

3

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.

Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

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.

Clodion
  • 1,017
  • 6
  • 12