this a question about code efficiency, not asking how to loop through layers. I'm getting the 'this question appears subjective...' warning but there must be a tried and tested method by someone more adept at PyQGIS programming than me! I don't intend to start a discussion, just hopefully someone more experienced can objectively say "do it like this instead" or "that's the best/only way".

I'm only just starting to use QGIS and PyQGIS to develop...stuff. Most of the operations I will be doing, and indeed all of them up until this point, will be using some layer that's in the map registry. So every function I have so far starts like this:

def some_function(layer, parameter, another_parameter):
    for lyr in iface.mapCanvas().layers():
        if lyr.name() == layer:
        # and then whatever it is I need to do or get from this layer

Is this the most efficient way of going about this, or is there another way of proceeding without looping through all layers and then having the if statement to ID the layer. Clearly the more layers you have open, the more computationally expensive this would be, perhaps there is a way of selecting the layer by its name directly?

1 Answer 1


You can select layers by name directly with:


It returns a list of all layers that name contains "layer_name".

  • sed -i s/contains/equals/' Jul 5, 2016 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.