Coulombeau Coulombeau - 1 year ago 92
Python Question

and operator on Python lists

I've found some really strange behavior in Python.
One of my students made some kind of mistake trying to find elements which belong to two lists, he wrote:

list1 and list2

The strange behavior is that no error is fired by Python 3!
list1 and list2
actually has got a value which is

Is there any known reason for this?

Answer Source

and simply evaluates the truthness of the two values provided. If the first is True (see bool(list1)) the second is evaluated and returned. If the first argument is False (e.g [] and list2) its value is returned immediately.

In the documentation on Boolean Operations the rationale for this behavior is stated clearly:

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.

(Emphasis mine)

Note that this behavior isn't found with not which, instead, returns a True/False value based on the argument provided.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download