I’m writing a program where I have to test if elements of a list are of a certain type. The list (z, found below) can get large and I could test the standard way:
for l in z:
typeL = type(l)
if typeL == complex or typeL == float:
#evaluate suite
elif typeL == list:
#evaluate different suite
Or, I can do the following:
for l in z:
lTemp = l*0
if lTemp == 0:
#evaluate suite
elif lTemp == []:
#evaluate different suite
My question is, which method is faster, more efficient, or preferred? Thanks to all in advance.
According to Zen of Python
So if you want to compare types, you should get types and compare them.
Clearer method is using
isinstance methodthat is accepting tuple-of-types argument. So your code may look like this:Also isinstance is compatible with ABC metaclasses, so you could be more straight and clear in your choises:
UPD: Answering to a question in commentary about perfomance, you should remember, that premature optimization is the root of all evil. When your program will work, you could analize it and find where the perfomance actually falls. Next you could optimize it in python, rewrite in cython or C, could use another implementation, etc. But while you are coding in python you must respect what is better for python code.