In Python, I know the pythonic way to check if a list is empty is
if not a:
# do things with empty list
To check if a list is not empty then, we would do:
if a:
# do things with my list
How would we check, simultaneously (as read), if two lists then are not empty?
if a and b:
# do things with my two lists
The above does not seem to work, and I'm unsure what (a and b)
actually means. For a = [2]
, b = [1,3]
, (a and b) = [1,3]
. What is the and
operator actually doing here? If I end up reducing b = []
at some point, (a and b) = []
even though a
is not empty.
Edit: My use case goes something like
while (a and b are not empty):
modify a
modify b
I would have naively thought that since if a
checks if a list is not empty, if a and b
would check if neither were empty, which is not the case.
An empty list is denoted using the [] . When a list object is compared with [] using == operator, then it returns True if the list object is empty. Else it returns False . Use the below snippet to check if the list is empty by comparing it with the empty list.
Using len() function To check an empty string in Python, use the len() function; if it returns 0, that means the string is empty; otherwise, it is not.
Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.
In python, we can write an empty function or statements by using the 'pass” statement. Writing a pass statement does nothing and is simply used to avoid compile errors while writing an empty function. Above code statements are little different than other popular programming languages like C,C++ or Java.
It's working fine. For a = [2]
and b = [1, 3]
, a and b
is returning [1, 3]
which is truthy, exactly as you would expect, because True and True
is True
. When you change b
to []
it returns []
, which is falsy, again exactly as you would expect, because True and False
is False
. So if a and b
does exactly what you want.
What is actually happening is that and
is returning the value that decided the truth of the expression. and
doesn't always evaluate both sub-expressions; when the first is falsy, the whole expression is falsy and the second doesn't need to be evaluated, and therefore isn't. This is called short-circuiting. or
behaves similarly (skipping evaluating the second part if the first part is truthy). Wherever and
or or
is able to make its decision, it returns that value.
Another way of looking at it: bool(a) and bool(a) == bool(a and b)
in Python.
a and b
is correct.
and
returns the second argument if the first is true.
You can do this
if len(a) and len(b):
#do something
I think what you want is
>>> a, b = list(), list()
>>> while not (a and b):
... a.append(1)
... b.append(2)
...
>>> a, b
([1], [2])
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With