Reputation: 125
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 list2
.
Is there any known reason for this?
Upvotes: 2
Views: 603
Reputation: 160447
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
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument. This is sometimes useful, e.g., ifs
is a string that should be replaced by a default value if it is empty, the expressions 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.
Upvotes: 5
Reputation: 113975
When you ask list1 and list2
, python calls the __bool__
on list1
and list2
. Since []
evaluates to False
, and a non-empty list evaluates to True
, and
looks at list1
and list2
in turn until it finds an empty list (or it looks at all the lists, if an empty list is never found).
Finally, the and
expression evaluates to either that empty list that makes the and
fail, or the last list in the comparison. This is why you get list2
back as the value.
Interestingly, you can use this behavior to your advantage to set default values:
def func(arg=None):
arg = arg or [5] # now, [5] is the default value of arg
This is practically the same as doing:
def func(arg=None):
if arg is None:
arg = [5]
Upvotes: 1
Reputation:
Well , if they both have values then the "if list1 and list2:" should return True and it will continue to the next line in the code. Python3 considers True if a variable is different then None or 0. Example:
a = 1
if a: #This will be True since a is different then None or 0
print("Works")
>>> Works
b = 0
if b:
print("Works")
>>>
This one returned nothing because b is 0 wich means that the "if b" will return False.
Also , it will return True on lists if the list has atleast 1 element in it.
Upvotes: 0