Another option is to use the ["Random selection"](https://docs.qgis.org/latest/en/docs/user_manual/processing_algs/qgis/vectorselection.html#random-selection) tool for selecting N *random* features.

<!-- language: pyqgis -->

    import processing
    
    layer = iface.activeLayer()
    
    processing.run("qgis:randomselection", {
                        'INPUT' : layer,
                        'METHOD' : 0,
                        'NUMBER' : 5 -- specify a number here
                        })

To get more information about this algorithm, please run the following command `processing.algorithmHelp("qgis:randomselection")` in the Python Console (<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>P</kbd>).

----------

**References:**

 - [PyQGIS Developer Cookbook » 21. Cheat sheet for PyQGIS](https://docs.qgis.org/latest/en/docs/pyqgis_developer_cookbook/cheat_sheet.html#cheat-sheet-for-pyqgis)