I am trying to select rows in a feature layer in QGIS based on the values in a list. I am using PyQGIS in the python console

If I just specify one item to find in a column called "gps_code", the feature(s) are selected

I would like to pass a list of items to achieve a selection of features based on that list and have tried to use a list comprehension for this but I am not getting the desired result

layer.selectByExpression('"gps_code" = \'DAAG\'')

list_of_sites = ['DAAG', 'ENTC', 'ENBR']
layer.selectByExpression('"gps_code" = \'s\' for s in list_of_sites')

What am I doing wrong?

1 Answer 1


Try using format and IN operator like:

list_of_sites = ('Arvika' , 'Avesta' , 'Arboga') #Note the tuple () and not list []
    'EXPRESSION':'"KOMMUNNAMN" IN{0}'.format(list_of_sites),

You can also list ids and select by them:

lyr = iface.activeLayer()
list_of_sites = ['Arvika', 'Avesta', 'Arboga' ]
fieldname = "KOMMUNNAMN"
lyr.select([f.id() for f in lyr.getFeatures() if f[fieldname] in list_of_sites])

enter image description here


Your Answer

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

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