I found this 3 ways to check it, but I don't know which of them is the best:
x = ['Bla', 'Bla', 'Bla', 'etc']
if isinstance(a, list): print('Perfect!')
if type(a) is list: print('Incredible!')
if type(a) == type([]): print('Awesome!')
Which of these is better?
Also, Can I use these ways to check whether an x is a string, tuple, dictionary, int, float, etc? If this is possible, in the first two methods do I have to convert a list to a tuple, string, dictionary, int, float, etc (no?), but in the third? I have to use (), {}, '', and what more for int and float?
Answer
These all express different things, so really it depends on exactly what you wish to achieve:
isinstance(x, list)
check if the type ofx
is eitherlist
or haslist
as a parent class (lets ignore ABCs for simplicity etc);type(x) is list
checks if the type ofx
is preciselylist
;type(x) == list
checks for equality of types, which is not the same as being identical types as the metaclass could conceivably override__eq__
So in order they express the following:
isinstance(x, list)
: isx
like alist
type(x) is list
: isx
precisely alist
and not a sub classtype(x) == list
: isx
a list, or some other type using metaclass magic to masquerade as alist
.
No comments:
Post a Comment