maya Finding scene objects Safely getting a single object from ls


Example

Many ls() queries are intended to find a single object, but ls always returns a list (or, in older Mayas, a single None). This creates complicated error checking for a simple question.

The easiest way to get a single value from an ls under any circumstances is

result = (cmds.ls('your query here') or [None])[0]

The or guarantees that at a minimum you'll get a list containing a single None so you can always index into it.

Note that this style won't tell you if you've got more than one result -- it just makes it safe to assume a single result.