Reputation: 197
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.
Upvotes: 1
Views: 959
Reputation: 16328
According to Zen of Python
So if you want to compare types, you should get types and compare them.
Clearer method is using isinstance method
that is accepting tuple-of-types argument. So your code may look like this:
for l in z:
if isinstance(l,(complex,float)):
#evaluate suite
elif isinstance(l,list):
#evaluate different suite
Also isinstance is compatible with ABC metaclasses, so you could be more straight and clear in your choises:
from numbers import Number
from collections import Iterable
for l in z:
if isinstance(l,Number):
#evaluate suite
elif isinstance(l,Iterable):
#evaluate different suite
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.
Upvotes: 12
Reputation: 3671
I am not sure, what you try to do, but since you have the two implementations (nearly) ready, you should benchmark them with your data, to decide which implementation is faster in your case.
I would be surprised to see a big difference in performance, only if #evaluate suite is a very cheap operation.
From a readability or maintainability point of view I would prefer the first one. The trick to do lTemp = l*0
is not very intuitive to me.
Upvotes: 2