Maximum value of vector layer field in PyQGIS

This does not work in qgis3. See below for updated answer


It is not necessary to get a complete list of field values. In QgsVectorLayer exists 'maximumValue' method. So, this works well and it's shorter:

layer = iface.activeLayer()

idx = layer.fieldNameIndex('fieldName')
print layer.maximumValue(idx)

You could use the following in the Python Console to print out the maximum value for a given field:

values = []
layer = qgis.utils.iface.activeLayer()
idx = layer.fieldNameIndex('fieldName')
for feat in layer.getFeatures():
    attrs = feat.attributes()
    values.append(attrs[idx])

print max(values)

The accepted answer does not work in QGIS3.

Now one has to do:

fieldname='id'
layer=iface.activeLayer()
idx=layer.fields().indexFromName(fieldname)
print(layer.maximumValue(idx))

(I am setting fieldname as the first line to make it easier to cut and paste for someone wanting to test it with their layer)