All we need to do is to use set()
method of $query
object.
It takes two arguments, first what we want to set and second what value to set.
add_action( 'pre_get_posts', 'change_posts_per_page' );
function change_posts_per_page( $query ) {
if( !$query->is_main_query() || is_admin() ) return;
$query->set( 'posts_per_page', 5 );
return;
}