PyQGIS Feature Selection – Selecting Multiple Features by ID-Attribute from List

featureslistpyqgisselect-by-expression

With PyQGIS I would like to use several "ID"s (in a list) to select certain objects in order to make them available later in a temporary layer. I know how to select one or a few more objects, but my list can contain a large number of "ID"s. My attempt to run

for x in list:
    layer.selectByExpression("id = '{}'".format(x))

in a for loop did not work. How can I select multiple features in a data set?

Best Answer

Use this way (without for loop):

id_list = [1, 2, 5]
layer.selectByExpression("id in {}".format(tuple(id_list)))
Related Question