Python: how to check if two lists are empty

In Python, I know that the pythonic method to check for an empty list is

if not a: # do things with empty list 

To check if the list is empty, we would do:

 if a: # do things with my list 

How will we check at the same time (as read) if the two lists are not empty?

 if a and b: # do things with my two lists 

The above doesn't work, and I'm not sure what (a and b) means. For a = [2] , b = [1,3] , (a and b) = [1,3] . What does the and operator really do? If I eventually reduce b = [] , (a and b) = [] , although a not empty.

Edit: my usage example looks something like

 while (a and b are not empty): modify a modify b 

I would naively think that since if a checks if the list is empty, if a and b will check if they were empty, which is not the case.

+6
source share
5 answers

It is working fine. For a = [2] and b = [1, 3] a and b returns [1, 3] , which is true, exactly as you would expect, because True and True are True . When you change b to [] , it returns [] , which is false, again exactly as you expected, because True and False - False . So if a and b does exactly what you want.

What actually happens is that and returns a value that resolves the truth of the expression. and does not always evaluate both subexpressions; when the first is false, the whole expression is false, and the second does not need to be evaluated, and therefore not. This is called squirrel cage. or behaves similarly (skipping the evaluation of the second part, if the first part is true). Wherever and or or could make a decision, it returns that value.

Another way to look at it: bool(a) and bool(a) == bool(a and b) in Python.

+6
source

a and b correct.

and returns the second argument if the first is true.

+2
source

You can do it

 if len(a) and len(b): #do something 
0
source
Operator

and compares two boolean values

  bool([]) == False 

therefore, [] and b always returns [] ; no matter what b .

0
source

I think you want

 >>> a, b = list(), list() >>> while not (a and b): ... a.append(1) ... b.append(2) ... >>> a, b ([1], [2]) >>> 
-1
source

Source: https://habr.com/ru/post/988027/


All Articles