9

I have a layer and I would like to access the number of rows the attribute table has from my code. Is there a way to do that without doing it like this:

num_of_features = 0

for feat in layer.getFeatures():
    num_of_features += 1

print(num_of_features)
1

3 Answers 3

17

Yes, there is a direct way to access the number of rows of your attribute table. Just call featureCount() method from your layer object:

num_of_features = layer.featureCount()
6

layer.getFeatures() is a Python Iterator (type: QgsFeatureIterator) so

num_of_features = len(list(layer.getFeatures()))

or you can use list comprehension:

num_of_features = len([feature for feature in layer.getFeatures()])
1

Another option can be the allFeatureIds() method from the QgsFeatureSource class:

num_of_features = len(layer.allFeatureIds())

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.