1

Consider the following code:

str1 = "Hi, how are you?"
str2 = "Fine."
str3 = "Goodbye."
print len(str1 and str2 and str3)

The last line always prints the length of the last argument of len().

Why does that happen, and how does the interpreter parse that expression? How is it even syntactically permissible to use the and keyword in len()?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

3

The real question is what str1 and str2 evaluates to, or actually what 'a' and 'b' evaluates to. It turns out that 'a' and 'b' evaluates to 'b'.

Therefore in your example, str1 and str2 and str3 evaluates to Goodbye. which explains why len(str1 and str2 and str3) is 8.

Interestingly enough, while 'a' and 'b' is 'b', 'a' or 'b' is 'a'.

Why?

I believe it has to do with Short-circuit evaluation. Since bool('a') (or any non-empty string) is True, the Python interpreter needs to evaluate True and True or in our second case, True or True.

For optimization reasons explained in the Wikipedia page I linked to, when evaluating True and True the second True will be returned but while evaluating True or True the first True can be returned (because True or anything will always be True there is no reason to bother evaluating the second term).

In order to get your desired result you should use the + operator:

str1 = "Hi, how are you?"
str2 = "Fine."
str3 = "Goodbye."
print len(str1 + str2 + str3)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154