In QGIS, what is the simplest python code (least possible) to verify if a particular layer is PRESENT or ABSENT in the Map Layers list?

NOTE: The script shouldn't trip an error IF the layer is ABSENT.

3 Answers 3

len(QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question')) != 0

Trueif layer exists, otherwise False

  • 4
    note that you could avoid the len(...) != 0 and just directly test the returned list, eg if QgsMapLayerRegistry.instance().mapLayersByName('the_Map_Layer_in_question'):
    – ndawson
    Jan 4, 2016 at 3:12

for those stumbling over this question; The accepted answer works for Qgis 2.x.

In Qgis 3.x the functionality of QgsMapLayerRegistry has been moved to QgsProject, so in pyqgis3 you need this (Documented here in the QGIS API Documentation) :

len(QgsProject.instance().mapLayersByName("the_Map_Layer_in_question")) != 0



 boolean = False
 layers = QgsMapLayerRegistry.instance().mapLayers()
 for name, layer in layers.iteritems():
     if layer.name() == ('the_Map_Layer_in_question'):
         boolean = True    
 # if the map layer exists boolean == True, if it doesn't boolean == False

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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