len(var) is [CONSTANT] equal to len(var) == [CONSTANT]?

Duncan Booth duncan.booth at invalid.invalid
Thu Nov 23 07:24:24 EST 2006


Tor Erik Soenvisen <toreriks at hotmail.com> wrote:

> I've seen code like this:
> 
> if type([]) is list:
>          print 'Is list'
> 
> which seem to work.

'seem to work' is correct. Occasionally 'type(x) is list' is exactly what 
is needed, but much more likely it is a potential bug.

It is more likely that what was intended was: isinstance(x, list)

It is even more likely that the intention was that the object should have 
some list-like behaviour, in which case not doing a test at all is the 
correct behaviour; or quite often that the object should be list-like but 
not a string in which case testing the type against basestring would be 
correct. e.g.:

if isinstance(x, basestring):
   x = [x]
# ... now just assume x is a suitable sequence ...
for element in x:
   ...



More information about the Python-list mailing list