maya Finding scene objects Dealing with ls() results


Using ls() as a filter can sometimes provide produce odd results. If you accidentally forget to pass a filter argument and call ls() with no arguments, you will get a list of every node in the Maya scene:
 # [u'time1', u'sequenceManager1', u'hardwareRenderingGlobals', u'renderPartition'...] etc

A common cause of this is using *args inside ls():["fred", "barney"]) # OK, returns ['fred', 'barney'][]) # OK, returns []*[]) # not ok: returns all nodes!

Maya 2015 and and earlier

In Maya 2015 and earlier, an ls() query which finds nothing will return None instead of an empty list. In case of using the result, it can result in an exception:

 for item in"don't_exist"):
     print item
 # Error: TypeError: file <maya console> line 1: 'NoneType' object is not iterable 

The cleanest idiom for working around this is always adding an alternative output when None is returned adding or [] after an ls() operation. That will ensure that the return is an empty list rather than None:

 for item in"don't_exist") or []:
     print item
 # prints nothing since there's no result -- but no exception