I was going through the Python Manual for 3.4 when I came across a built in function that I didn't know about. The function was any(x).
The Python Manual said that this function "Return True if any element of the iterable is true. If the iterable is empty, return False."
They also wrote code that would be equivalent to this function.
def any(iterable):
for element in iterable:
if element:
return True
return False
What are the uses of this function?
You can use it to avoid multiple similar conditions, for example.
To check if a string contains a list of substrings, you can do:
str = 'Your cat is hungry.'
if 'cat' in str:
print 'Feed it!'
elif 'dog' in str:
print 'Feed it!'
elif 'hamster' in str:
print 'Feed it!'
...or you can do:
str = 'Your cat is hungry.'
pets = ['cat', 'dog', 'hamster']
if any(animal in str for animal in pets):
print 'Feed it!'
Update: if element: return True.
You are correct - if an element in the iterable has a value, it's True. In Python, basically if variable has a value, it's True - obviously, as long as the value isn't False. Run that example and look at the values and the conditions, maybe it helps more than explanations:
x = ' '
y = ''
z = False
if x:
print 'x is True!'
else:
print 'x is False!'
if x == True:
print 'x is True!'
else:
print 'x is False!'
if y:
print 'y is True!'
else:
print 'y is False!'
if z:
print 'z is True!'
else:
print 'z is False!'
Now back to any(): It takes any iterable, like a list, as an argument - and if any value of that iterable is True (hence the name), any() returns True.
There is also a function called all() - it's similar to any(), but only returns True if all values of the iterable are true:
print any([1, 2, False])
print all([1, 2, False])
True and False
It's been mentioned in a comment by #Burhan Khalid before, but the official docs about what's considered to be False should be mentioned here, too:
Truth Value Testing
the any function in python is just like a parallel connection of switches in a circuit if you like physics.
If any one of the switch is on ,(if element) the circuit will be completed and it will glow a bulb connected to it in a series connection.
lets take bulb in the parallel connection as shown in figure as circuits and
the bulb as the indicator bulb(the result of any)
for an instance , if you have a logical list of True and False,
logical_list = [False, False, False, False]
logical_list_1 = [True, False, False, False]
any(logical_list)
False ## because no circuit is on(True) all are off(False)
any(logical_list_1)
True ## because one circuit is on(True) remaining three are off(False)
or you can think of it as a connection of AND, so if any one of the value of the iterator is False, the Result will be False.
For the case of Strings, scenario is same, just the meaning has been changed
'' empty string -> False
'python' non empty string -> True
try this :
trial_list = ['','','','']
trial_list_1 = ['python','','','']
any(trial_list)
False ## logically trial_list is equivalent to [False(''), False(''), False(''), False('')]
any(trial_list_1)
True ## logically trial_list_1 is equivalent to [True('python'), False(''), False('') , False('')]
for the case of single non empty string any(non empty string) is always True
for the case of single empty string any(empty string is always False
any('')
False
any('python')
True
I hope this helps ,,
Related
I am new to python
I have a list of flags. and that list has a variable length. I want to check if all the variables in that list are true
I have tried
if (all in flags[x]==True):
finalFlags[x-1]=True
But that turned the final flag true when only one flag is true
finalFlags = False
if all(flags):
finalFlags=True
Edit: Simplified per comment from Chris:
finalFlags = all(flags)
Since you didn't post an example, i can suppose like this:
my_flags = [True, False, True, True, True, False]
valid_flags = 0
for flag in my_flags:
if flag == True:
valid_flags += 1
if len(my_flags) == valid_flags:
print("Total match")
else:
print("Matched ", valid_flags, " out of ", len(my_flags))
all and any functions can be used to check the boolean values inside the list.
test_list = []
all(iterable) returns True if all elements of the iterable are considered as true values (like reduce(operator.and_, iterable)).
any(iterable) returns True if at least one element of the iterable is a true value (again, using functional stuff, reduce(operator.or_, iterable)).
When you need to check all the values are true then you can use all() function as follow
all(test_list) #will return true
Also, you can use any() to check all values that are true but at this time, You need to convert the list elements from true to false and check whether if any true is there we can say there is a false in original list and we need to return false also when any() returns false which means there is no true value so in the original list we don't have true values
not all(not element for element in data)
I just stumbled across this and I couldn't find a sufficient answer:
x = ""
Why then is:
x == True
False
x == False
False
x != True
True
x != False
True
Am I supposed to conclude that x is neither True nor False?
to check if x is True of False:
bool("")
> False
bool("x")
> True
for details on the semantics of is and == see this question
Am I supposed to conclude that x is neither True nor False?
That's right. x is neither True nor False, it is "". The differences start with the type:
>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool
Python is a highly object oriented language. Hence, strings are objects. The nice thing with python is that they can have a boolean representation for if x: print("yes"), e. g.. For strings this representation is len(x)!=0.
In a Boolean context, null / empty strings are false (Falsy). If you use
testString = ""
if not testString:
print("NULL String")
else:
print(testString)
As snakecharmerb said, if you pass the string to the bool() function it will return True or False based
>>> testString = ""
>>> bool(testString)
False
>>> testString = "Not an empty string"
>>> bool(testString)
True
See this doc on Truth Value Testing to learn more about this:
Python 2:
https://docs.python.org/2/library/stdtypes.html#truth-value-testing
Python 3:
https://docs.python.org/3/library/stdtypes.html#truth-value-testing
In python '==' tests for equality. The empty string is not equal to True, so the result of your comparison is False.
You can determine the 'truthiness' of the empty string by passing it to the bool function:
>>> x = ''
>>> bool(x)
False
I'm going through Zed's "Learn Python The Hard Way" and I'm on ex49. I'm quite confused by the following code he gives:
def peek(word_list):
if word_list: # this gives me trouble
word = word_list[0]
return word[0]
else:
return None
The condition of the if statement is giving me trouble, as commented. I'm not sure what this means as word_list is an object, not a conditional statement. How can word_list, just by itself, follow if?
The if statement applies the built-in bool() function to the expression which follows. In your case, the code-block inside the if statement only runs if bool(word_list) is True.
Different objects in Python evaluate to either True or False in a Boolean context. These objects are considered to be 'Truthy' or 'Falsy'. For example:
In [180]: bool('abc')
Out[180]: True
In [181]: bool('')
Out[181]: False
In [182]: bool([1, 2, 4])
Out[182]: True
In [183]: bool([])
Out[183]: False
In [184]: bool(None)
Out[184]: False
The above are examples of the fact that:
strings of length >= 1 are Truthy.
empty strings are Falsy.
lists of length >= 1 are Truthy.
empty lists are Falsy.
None is Falsy.
So: if word_list will evaluate to True if it is a non-empty list. However, if it is an empty list or None it will evaluate to False.
He is checking if word_list is empty or not. If a list is empty and it is used in a conditional statement, it is evaluated to False. Otherwise, it is evaluated to True.
word_list = ['some value']
if word_list:
# list is not empty do some stuff
print "I WILL PRINT"
word_list = []
if word_list:
# list is empty
print "I WILL NOT PRINT"
In the above code, only the first snippet will print.
See the following reference: https://docs.python.org/2/library/stdtypes.html#truth-value-testing
word_list is a list and when you use it for an if statement condition you check word_list is empty or not :
word_list = []
bool(word_list) # False
if word_list :
print "I'm not empty" # would not printed
word_list = ['a']
bool(word_list) # True
if word_list :
print word_list[0] # 'a'
as Mad Physicist said even None elements in a list means that it's not empty:
word_list = [None]
bool(word_list) # True
What is required for an if block is just something that can be evaluated either to True or to False. A conditional evaluates directly to one of those, but there are other objects that can be converted. To see what any given object is, you can use bool:
>>> mylist = []
>>> bool(mylist)
False
>>> mylist = [4, 3, 6]
>>> bool(mylist)
True
You see, a list is False if it is empty, but True otherwise. Therefore, the if word_list: block will be evaluated if word_list is nonempty. Strings also are False if they are empty, but True otherwise. Same thing with tuples, dictionaries, sets. With numbers, 0 and 0.0 are False, but any other number is True. A fairly common argument to give to indicate to the function to come up with its own value is None which evaluates to False, so the if not mylist: block will be executed if mylist is empty or if mylist is None. (It would also be executed if mylist is 0, (), {}, etc.; but it's unlikely that mylist would be given those)
Take a look at this docs page for Truth Value Testing in python. You should get clear idea about your situation after reading this. Here is the relevant part for easy access.
5.1. Truth Value Testing
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:
None
False
zero of any numeric type, for example, 0, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __bool__()
or __len__() method, when that method returns the integer zero or bool
value False.
All other values are considered true — so objects of many types are always true.
Read the first sentence (bolded) again, and note the bolded parts in the fourth rule. This relates to your question.
So, according to the 4th rule, if your word_list is empty, the condition evaluates to False, otherwise it evaluates to True.
I know you trust in the docs, but here is a code snippet to actually test the truth values for yourself. (I know it is needless to do something like this, but I am always tempted to see things with my own eyes)
def test_truth_value(arg):
# ANY object can be evaluated for truth or false in python
if arg: # or to be more verbose "if arg is True"
print("'{}' is True".format(arg))
else:
print("'{}' is False".format(arg))
class dummy_length_zero():
def __len__(self):
return 0
def __str__(self):
return 'instance of class: "dummy_length_zero"'
class dummy_bool_False():
def __bool__(self):
return False
def __str__(self):
return 'instance of class: "dummy_bool_False"'
obj_dummy_0 = dummy_length_zero()
obj_dummy_false = dummy_bool_False()
args = [None, False, 0, 0.0, 0j, '', (), [], {}, obj_dummy_0, obj_dummy_false]
for arg in args:
test_truth_value(arg)
And lastly, to test that last statement so objects of many types are always true, just remove the implementation of __len__() or __bool__() method from dummy_length_zero or dummy_bool_False class respectively, and check for truth.
In python, everything has an implicit boolean value. Putting any object in an if statement directly is equivalent (but more Pythonic than) doing if bool(word_list):. None, empty sequences, empty sets, empty dicts, 0, False, 0.0 all evaluate to False. Most other objects evaluate to True. That makes if word_list: the most Pythonic way of ensuring that the list is not None or empty before accessing the first element. The long way of expressing the same thing would be if word_list is not None and len(word_list) > 0:.
In Python, every expression can be evaluated to a boolean value (i.e. either True or False).
The following, basic, expressions evaluate to False
The keyword False (obviously!)
The keyword None
The number 0 (0, 0.0 ... )
empty sequence (tuple, list, string)
empty mapping (dictionary)
All other expressions evaluate to True.
So, what the if statement does is evaluating the expression that follows the if keyword to either True or False, then act accordingly.
So in your specific example, if word_list matches any of the above cases it will be considered False, otherwise, it will be considered True.
[#] reference
def name(x):
return x==('Jenson'or'Amra'or'McCay'or'Spinner'or'Jones')
print(name('Jenson'))
print(name('McCay'))
This is the question:
"Write a function that takes as input a name of a person (e.g.,
“smith”, “jones”, etc.) This function should check to see if the name
is one of the five names of people on the board. The five names are:
“Jenson”,”Amra”, “McCay”,”Spinner”, and “Jones”. If the name input
into the function is one of those five names, the function should
return the Boolean value True, and if it isn’t, the function should
return False. (remember comments with input types, description, and
test cases) Test the function to make sure it works."
It works if I am doing Jenson but it comes out with false if I put in any other name.
Try like this,
def name(x):
return x in ('Jenson', 'Amra' ,'McCay', 'Spinner','Jones')
How about the "long" way:
def check_name(x):
names_to_check = ('Jenson','Amra','McCay','Spinner','Jones')
for i in names_to_check:
if i == x:
return True
return False
Here is what is happening in your code:
x = 'Jenson', since this is what you have passed in.
This line x == ('Jenson' or 'Amra' or 'McCay' or 'Jones') is actually a boolean operation, and the result of it is always Jenson.
Boolean operations check truth values, and a non-empty string in Python is always True. So actually what ('Jenson' or 'Amra' or 'McCay' or 'Jones') is saying is:
"Either Jenson or Amra or McCay or Jones which ever one is True, set the value to that".
Since Jenson is the first item, and its True (that is, its not an empty string), the entire expression is equal to Jenson (which is why it only works when you pass in Jenson).
A simple example:
>>> ('a' or 'b' or 'c')
'a'
>>> ('b' or 'a' or 'c')
'b'
>>> ('' or '' or 'a')
'a'
>>> (0 or 0 or 1)
1
>>> (False or False or True)
True
The last three illustrate the same comparison. I am checking two empty strings and 'a'. Since an empty string is False in Python, the only thing that is "True" is 'a', which is what is returned, just as if I was comparing 0 with 1.
The syntax x==('Jenson' or 'Amra' or 'McCay' or 'Spinner'or'Jones') is wrong.
It should be like Adem says. or maybe
def name(x):
return x=='Jenson' or x== 'Amra' or x == 'McCay' or x == 'Spinner' or x == 'Jones'
I imagine what is happening is that ('Jenson'or'Amra'or'McCay'or'Spinner'or'Jones') is being evaluated first, and is evaluated to 'Jenson'. That is computed before x is even considered because it is in parentheses. Then x is checked for equality against Jenson. You need to either use a more advanced syntax like x in... as in Adem's answer, or else use return x == 'Jenson' or x == 'Amra' or x == 'McCay'... so that each comparison is run one after another.
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