Design a logical expression equivalent to the following statement:
x is a list of three or five elements, the second element of which is
the string 'Hip' and the first of which is not a number or Boolean.
What I have:
x = ['Head', 'Hip', 10]
print x[1] is 'Hip'
My question: How do you check for whether or not it is a Boolean or a number?
To answer the specific question:
isinstance(x[0], (int, float))
This checks if x[0] is an instance of any of the types in the tuple (int, float).
You can add bool in there, too, but it's not necessary, because bool is itself a subclass of int.
Doc reference:
isinstance()
built-in numeric types
To comment on your current code, you shouldn't rely on interning of short strings. You are supposed to compare strings with the == operator:
x[1] == 'Hip'
Easiest i would say:
type(x) == type(True)
In python3 this would be: type(x)==bool see example.
Python 2
import types
x = False
print(type(x) == types.BooleanType) # True
Python 3
# No need to import types module
x = False
print(type(x) == bool) # True
You should compare the type of x to the bool class:
type(x) == bool
or:
type(x) == type(True)
Here is more on the type method
From Data model docs:
Booleans (bool)
These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
I follow the recent answer who tell to use type and it seems to be the incorrect way according to pylint validation:
I got the message:
C0123: Using type() instead of isinstance() for a typecheck.
(unidiomatic-typecheck)
Even if it's an old answer, the correct one is the accepted answer of #Lev Levitsky:
isinstance(x[0], (int, float))
Python 3:
Use assert to check is some statement is True or False. If False, it will raise an AssertionError.
assert(isinstance(x[0], (int, float)))
You can then catch the error like that:
except AssertionError as error:
print(error)
# do stuff...
I like to keep it simple to read..
This will accept bool, string, number and read it to a bool
def var2bool(v):
if type(v) == type(True):
res = v
elif type(v) == type(0):
if v == 0:
res = False
else:
res = True
elif v.lower() in ("yes", "true", "t", "1"):
res = True
else:
res = False
return res
Related
I am checking whether a list in python contains only numeric data. For simple ints and floats I can use the following code:
if all(isinstance(x, (int, float)) for x in lstA):
If there any easy way to check whether another list is embedded in the first list also containing numeric data?
You can do a recursive check for all lists within the list, like so
def is_all_numeric(lst):
for elem in lst:
if isinstance(elem, list):
if not is_all_numeric(elem):
return False
elif not isinstance(elem, (int, float)):
return False
return True
print(is_all_numeric([1,2,3]))
>>> True
print(is_all_numeric([1,2,'a']))
>>> False
print(is_all_numeric([1,2,[1,2,3]]))
>>> True
print(is_all_numeric([1,2,[1,2,'a']]))
>>> False
I don't know if there is another way to do this, but you could just do a for loop for each item, and if any of those items is not a number, just set on bool to false:
numbers = [1,2,3,4,5,6,7,8]
allListIsNumber = True
for i in numbers:
if i.isnumeric() == False:
allListIsNumber = False
You can either use isnumeric() or isinstance()
Assume that x is a string variable that has been given a value. Write an expression whose value is true if and only if x is NOT a letter.
def isLetter(ch):
import string
return len(ch) == 1 and ch in string.ascii_letters
print(isLetter('A'))
True
If you want to check the type of the variable x, you can use the following:
if type(x) is str:
print 'is a string'
In python, String and Char will have the same type and same output unlike languages like java.
type(chr(65)) == str
type('A') == str
EDIT:
As #Kay suggested, you should use isinstance(foo, Bar) instead of type(foo) is bar since isinstance is checking for inheritance while type does not.
See this for more details about isinstance vs type
Using isinstance will also support unicode strings.
isinstance(u"A", basestring)
>>> true
# Here is an example of why isinstance is better than type
type(u"A") is str
>>> false
type(u"A") is basestring
>>> false
type(u"A") is unicode
>>> true
EDIT 2:
Using regex to validate ONLY ONE letter
import re
re.match("^[a-zA-Z]$", "a") is not None
>>> True
re.match("^[a-zA-Z]$", "0") is not None
>>> False
Turns out the answer to it is not((x>='A' and x<='Z') or (x>='a' and x<='z'))
Use regular expression. http://www.pythex.org is a good learning spot, official docs here: https://docs.python.org/2/library/re.html
something like this should work though:
if x != '[a-zA-Z]':
Suppose,
var = ('x', 3)
How to check if a variable is a tuple with only two elements, first being a type str and the other a type int in python?
Can we do this using only one check?
I want to avoid this -
if isinstance(var, tuple):
if isinstance (var[0], str) and (var[1], int):
return True
return False
Here's a simple one-liner:
isinstance(v, tuple) and list(map(type, v)) == [str, int]
Try it out:
>>> def check(v):
return isinstance(v, tuple) and list(map(type, v)) == [str, int]
...
>>> check(0)
False
>>> check(('x', 3, 4))
False
>>> check((3, 4))
False
>>> check(['x', 3])
False
>>> check(('x', 3))
True
Well considering tuples are variable in length you're not going to find a method that checks this instance of all it's types. What's wrong with the method you have? It's clear what it does and it fits your usage. You're not going to find a pretty one liner AFAIK.
And you do have a one liner... Technically:
def isMyTuple(my_tuple):
return isinstance(my_tuple,(tuple, list)) and isinstance(my_tuple[0],str) and isinstance(my_tuple[1],int)
var = ('x', 3)
print isMyTuple(var)
If you're going to do this check many times, calling the method is DRY!
Not exactly what you ask for, but you might find it useful.
from itertools import izip_longest
def typemap(iterable, types, *indexes):
# izip_longest helps with the length check, because we will get a TypeError if len(iterable) > len(types)
try:
_iterable = ((elem for ind, elem in enumerate(iterable)
if ind in indexes) if indexes else iterable)
return all(isinstance(elem, _type)
for elem, _type in izip_longest(_iterable, types))
except TypeError:
return False
typemap((1, 2, "ch", {}, []), (int, int, str, dict, list)) # -> True
typemap((1, 2, "ch", {}, []), (int, int, str, dict)) # -> False
typemap((1, 2, "ch", {}, []), (int, int, str, list), 0, 1, 2, 4) # -> True
You can chain all your ifs on one line:
result = isinstance(var, tuple) and isinstance(var[0], str) and isinstance(var[1], int)
result will be True is all conditions match, else it'll be False
You can pass a tuple of arguments to isinstance to test for a list or a tuple:
def test(t):
return isinstance(t, (tuple, list))and len(t) == 2 and\
isinstance(t[0], str) and isinstance(t[1], int)
If you only want to accept either lists or tuples with two elements you need the check for the length, if it did not have to be 2 you would still need to make sure it had at least two elements to avoid an indexError
You could go down the route of begging forgiveness:
def isMyTuple( var):
try:
return isinstance(var, tuple) and \
isinstance (var[0], str) and \
isinstance(var[1], int)
except:
return False
I'm not entirely certain you need the try ... except in this case. Python uses short-circult logic. If it's not a tuple the second and third tests don't get executed and so you don't crash out trying to index a non-indexable var. But just possibly, someone derived a class from Tuple and modified it so its indexes aren't integers, or some other wierdness.
BTW should you should also check len(var)==2 ?
You can write your own function that checks if a variable matches a specification:
def istype(var, spec):
if type(var) != type(spec):
return False
if isinstance(spec, tuple):
if len(var) != len(spec):
return False
return all([istype(var[i], spec[i]) for i in range(len(var))])
return True
You have to add more checks for other types, but for your example this will suffice.
>>> istype((1,'x'), (2,'y'))
True
I want to make condition than number has to be integer. And x == int(x) doesn't help in cases when x == 1.0...
Thank you.
isinstance(x, (int, long))
isinstance tests whether the first argument is an instance of the type or types specified by the second argument. We specify (int, long) to handle cases where Python automatically switches to longs to represent very large numbers, but you can use int if you're sure you want to exclude longs. See the docs for more details.
As for why 1.0 == 1, it's because 1.0 and 1 represent the same number. Python doesn't require that two objects have the same type for them to be considered equal.
Not big on python, but I used this to check:
i = 123
f = 123.0
if type(i) == type(f) and i == f:
print("They're equal by value and type!")
elif type(i) == type(f):
print("They're equal by type and not value.")
elif i == f:
print("They're equal by value and not type.")
else:
print("They aren't equal by value or type.")
Returns:
They're equal by value and not type.
Just check if it's an integer.
>>> def int_check(valuechk, valuecmp):
if valuechk == valuecmp and type(valuechk) == int:
return True
else:
return False
>>> int_check(1, 1)
True
>>> int_check(1.0, 1)
False
Python converts the integer value into its real equivalent, then checks the two values, and thus the answer is true when checking value equivalence, but if one is checking type equivalence then the answer is false.
I did several Boolean Comparisons:
>>> (True or False) is True
True
>>> (True or False) == True
True
It sounds like == and is are interchangeable for Boolean-values.
Sometimes it's more clear to use is
I want to know that:
Are True and False pre-allocated in python?
Is bool(var) always return the same True(or False) with the pre-allocated True(or False)?
Is it safe to replace == with is to compare Boolean-values?
It's not about Best-Practice.
I just want to know the Truth.
You probably shouldn't ever need to compare booleans. If you are doing something like:
if some_bool == True:
...
...just change it to:
if some_bool:
...
No is or == needed.
As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use == or != rather than is or is not (the reason is explained below). Note that this is logically equivalent to xnor and xor respectively, which don't exist as logical operators in Python.
Internally, there should only ever be two boolean literal objects (see also the C API), and bool(x) is True should be True if bool(x) == True for any Python program. Two caveats:
This does not mean that x is True if x == True, however (eg. x = 1).
This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence == is a more reliable comparison.
Watch out for what else you may be comparing.
>>> 1 == True
True
>>> 1 is True
False
True and False will have stable object ids for their lifetime in your python instance.
>>> id(True)
4296106928
>>> id(True)
4296106928
is compares the id of an object
EDIT: adding or
Since OP is using or in question it may be worth pointing this out.
or that evaluates True: returns the first 'True' object.
>>> 1 or True
1
>>> 'a' or True
'a'
>>> True or 1
True
or that evaluates False: returns the last 'False' object
>>> False or ''
''
>>> '' or False
False
and that evaluates to True: returns the last 'True' object
>>> True and 1
1
>>> 1 and True
True
and that evaluates to False: returns the first 'False' object
>>> '' and False
''
>>> False and ''
False
This is an important python idiom and it allows concise and compact code for dealing with boolean logic over regular python objects.
>>> bool([])
False
>>> bool([0])
True
>>> bool({})
False
>>> bool({False: False})
True
>>> bool(0)
False
>>> bool(-1)
True
>>> bool('False')
True
>>> bool('')
False
Basically 'empty' objects are False, 'non empty' are True.
Combining this with #detly's and the other answers should provide some insight into how to use if and bools in python.
Yes. There are guaranteed to be exactly two bools, True and False:
Class bool cannot be subclassed
further. Its only instances are False
and True.
That means if you know both operands are bool, == and is are equivalent. However, as detly notes, there's usually no reason to use either in this case.
It seems that all answers deal with True and False as defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects:
>>> True = 1
>>> (2 > 1)
True
>>> (2 > 1) == True
True
>>> (2 > 1) is True
False
If you have to deal with older software, be aware of that.
The == operator tests for equality The is keyword tests for object identity. Whether we are talking about the same object. Note, that more variables may refer to the same object.
== and is are both comparison operators, which would return a boolean value - True or False. True has a numeric value of 1 and False has a numeric value of 0.
The operator == compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator is tests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects.
So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use is.
42 is 42 is True and is same as 42 == 42.
Another reason to compare values using == is that both None and False are “falsy” values. And sometimes it’s useful to use None to mark a value as “not defined” or “no value” while considering True and False values to work with:
def some_function(val = None):
"""This function does an awesome thing."""
if val is None:
# Values was not defined.
elif val == False:
# User passed boolean value.
elif val == True:
# User passed boolean value.
else:
# Quack quack.
Somewhat related question: Python != operation vs “is not”.