This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does “[] == False” evaluate to False when “if not []” succeeds?
I am new to python as per ternary operator of python
>>> 'true' if True else 'false' true
true
i am expecting for below code output as [] because [] not equal to None
>>> a=[]
>>> a==None
False
>>> a if a else None
None
pleas correct if i am wrong
Thanks
hema
The empty list, [], is not equal to None.
However, it can evaluate to False--that is to say, its "truthiness" value is False. (See the sources in the comments left on the OP.)
Because of this,
>>> [] == False
False
>>> if []:
... print "true!"
... else:
... print "false!"
false!
None is the sole instance of the NoneType and is usually used to signify absence of value. What happens in your example is that the empty list, taken in boolean context, evaluates to False, the condition fails, so the else branch gets executed. The interpreter does something along the lines of:
>>> a if a else None
[] if [] else None
[] if False else None
None
Here is another useful discussion regarding None: not None test in Python
Related
This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 3 years ago.
In C/C++, true is standardized as 1, and false as 0. Although not a good practice,
if variable:
#do something
kind of decision making seems ok in python and it seems makes decision based on whether variable is None or is zero - if it is a number. Followings are reasonable.
a = 123123
if a:
print "if condition is true" # this prints
a = "a string"
if a:
print "if condition is true" # this prints
a = None
if a:
print "if condition is true" # this does not print
However, I wonder why it evaluates to false with an empty list, which is neither None, nor zero. What is the exact implementation of python if statement?
a = [] # a is not None
if a:
print "true" # this does not print
An if statement requires a bool. That means the the expression following the if is analyzed is a boolean context. Said differently it is converted to bool.
If a bool context, the following items evaluate to False (non exhaustive list):
None
numeric 0
empty list
empty string
empty dict
Non null numerics and non empty iterables eveluate to True
Lists are empty, so they're False, that's how python reacts, to know whether something is False so doesn't go trough, do:
>>> bool([])
False
>>>
So it is False.
This question already has answers here:
Empty list boolean value
(3 answers)
Closed 4 years ago.
I am relatively new to Python and don't understand the following behavior:
Why does the statement
[] == False
evaluate to false, eventhough an empty list is falsy?
Here are more examples - in many other cases it seems that the empty list does behave in a falsy way, just not in [] == False...
>>> 0 == False # what I'd expect
True
>>> not [] # what I'd expect
True
>>> bool([]) # what I'd expect
False
>>> [] == True # what I'd expect
False
>>> [] == False # unexpected
False
>>> bool([]) == False # why does it evaluate to True again now?
True
>>> ([]) == (bool([])) # unexpected
False
>>> (not []) == (not bool([]) # apparently adding 'not' makes it behave as expected again - why?
True
Can somebody please explain this to me? How are these statements internally evaluted? I have a feeling it might be related to chaining comparisons (see e.g. here), but cannot really understand if that's correct and why.
Because falsy isn't False. Falsy just means
bool(some_object) is False
So,
>>> bool([]) is False
True
>>> bool({}) is False
True
>>> bool(0) is False
True
This question already has answers here:
Is short-circuiting in assignment statements considered good style?
(2 answers)
Closed 7 years ago.
I was reading through an API's documentation when I came across a curious little set of statements:
self.use_ssl = kwargs.get('use_ssl', True)
self.scheme = self.use_ssl and 'https://' or 'http://'
After doing some personal testing, I found that if self.use_ssl was set to True, self.scheme would be set to use HTTPS, and HTTP if self.use_ssl was False. Awesomely pythonic, and I'll definitely be stealing this.
Can somebody explain exactly how this works?
In python, an empty string is equivalent to False, a non empty string is equivalent to True
>>> bool('')
False
>>> bool('foo')
True
The behavior of a boolean expression is described in the python 2 documentation, and is the same for python 3.
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
That's why you get the string 'https://' or 'http://' depending on the value of 'self.use_ssl'
Some examples, from the python console:
>>> True or ''
True
>>> True or 'foo'
True
>>> False or ''
''
>>> False or 'foo'
'foo'
>>> '' or True
True
>>> '' or False
False
>>> 'bar' or True
'bar'
>>> 'bar' or False
'bar'
>>> True and ''
''
>>> True and 'foo'
'foo'
>>> False and ''
False
>>> False and 'foo'
False
>>> '' and True
''
>>> '' and False
''
>>> 'bar' and True
True
>>> 'bar' and False
False
You can always convert a boolean expression to a real boolean value using bool()
>>> 1 and 'bar'
'bar'
>>> bool(1 and 'bar')
True
This trick, a and b or c, only works when b itself is a "truthy" value. Consider True and "" or "foo". You might expect it to produce the empty string, but it will produce foo, because True and "" results in the empty string, which is considered False when evaluating "" or "foo". The correct way would be to wrap b and c in a list to guarantee that the second argument to and is truthy (and that the overall result is a list in either case), then extract the first value of that list:
(a and [b] or [c])[0]
To avoid the clunkiness (and inefficiency) of creating and indexing a temporary list, Python introduced the conditional expression:
b if a else c
which does not rely on b having any particular boolean value.
it works like this:
when python interapt this it first checks the self.use_ssl if it is True
it continues in the AND chain to see if the next statement is True.
since the next statement is a string (and not an empty one) it is True
so there is no need to continue to the or since this statement is definetly True already, so the last value is used witch was 'https'
if use_ssl was false then there is no need to evaluate the and part of the condition since the first part is already false so python "skip" it and continue to the or part to check if that is True, since it is again a non empty string it is true, and again the last value used is "returned"
This question already has answers here:
Python "all" function with conditional generator expression returning True. Why?
(2 answers)
Closed 9 years ago.
have a question on all() operator in Python.
say
array = ["one","one","one"]
all( x=="one" for x in array ) <<--- i want to check for all "one" in array
The above seem to work. however, if i have
array = []
all( x=="one" for x in array ) <<--- this still return true to me.
The behaviour is that i want it return false if all items are not "one". How to do it? thanks
You can read all() as if it means:
It returns False if any of the items evaluates to False. True otherwise.
So an empty set will return True, because there is none that will make it false.
Generally speaking, in an empty set, all the elements fullfill any requirement you can imagine. That's a principle of logic, not of Python, BTW.
all's implementation is equivalent to this
def all(iterable):
for element in iterable:
if not element:
return False
return True
So, it returns True till any of the elements in the iterable is Falsy. In your case that didnt happen. Thats why it returns True
all always returns True for an empty list/tuple/etc. This is because, technically, every item in an empty collection fulfills any and every condition there is.
To fix the problem, you need to add some additional code to test whether your list is empty or not. Fortunately, empty lists evaluate to False in Python, so you can just do this:
>>> array = []
>>> bool(array and all(x=="one" for x in array))
False
>>> if array and all(x=="one" for x in array):
... print True
... else:
... print False
...
False
>>>
How to do it?
array and all(x=="one" for x in array)
Empty lists are false, so the result is false and it doesn't matter that the all part is true.
If you want to deal with iterables other than containers like list then it's a bit harder. I suppose you need something like this:
set(x=="one" for x in iterable) == { True }
Although if you care about speed, the following should be faster on the whole, since the version above doesn't short-circuit like all does:
def nonempty_all(iterable):
iterator = iter(iterable)
try:
if not next(iterator):
return False
except StopIteration:
return False
return all(iterator)
I was testing a list to see if it's empty or not. Normally I use len(list) == 0 and I vaguely remembered reading a little while ago that the correct way to test if a list is empty was whether it was True or false.
So I tried list is False, and that returned False. Maybe I'm suppose to be using == ?
Nope, that also returned false. list is True, returned false as did list == True.
Now I'm confused so I do a quick google and end up at: Best way to check if a list is empty
The top answer is:
if not a:
print "List is empty"
So I search around some more and end up in the python manual where 4.1 states:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
any empty sequence, for example, '', (), [].
Now I'm plain confused. If I test a list as if not list, it works fine. But if an empty list is false, then why can't I just do if list is False or if list == False?
Thanks
An empty list is not False, but when you convert it to a boolean, it converts to False. Likewise for dicts, tuples, strings, etc.:
>>> [] == False
False
>>> bool([]) == False
True
>>> {} == False
False
>>> bool({}) == False
True
When you put something in the condition of an if clause, it is its boolean value that is used for testing the if. That's why if someList is the same as if bool(someList). Likewise, not foo does a boolean not, so not [] equals True.
As other have said, in python bool([]) == False. One thing that is frequently exploited by python programmers is that the operators and and or don't (necessarily) return True/False. Consider the following:
3 and 4 #returns 4
0 and 8 #returns 0 -- This is short-circuit evaluation
0 or 8 #returns 8
True or 0 #returns True -- This is short-circuit evaluation
[] or False #returns False
False or [] #returns []
What happens in an if statement is that the condition gets evaluated as above and then python implicitly calls bool on the result -- So you can think of it as:
if condition:
is the same thing as:
if bool(condition):
as far as python is concerned. Similarly for the not operator:
not condition
is the same thing as
not bool(condition)
mylist is False means "is the object named mylist exactly the same object as False?"
mylist == False means "is the object named mylist equal to False?
not mylist means "does the object named mylist behave falsily?
None of these are equivalent: 1 is not 1.0 but 1 == 1.0 and [] != False but not [] is True.
Comparing the list to False, and testing the list's truth or falsehood aren't quite the same thing. An empty list isn't equal to False, but behaves as False in a boolean context.
Here's another way to say it that might help this make sense:
print (bool([]) == False) # will print True
print ([] == False) # will print False