Creating a page number array for pagination
1. Review


The function needs a docstring to explain what it does, with maybe some examples. The explanation in your post is very good: this is exactly the kind of thing that should go into the docstring.
The number 5 is arbitrary, so I would make it a parameter to the function.
The implementation takes time proportional to the number of entries in the page range. It would be more elegant to compute the endpoints of the range directly, taking constant time.


2. Revised code

def page_range(page, last, span=5):
    """Return a range of page numbers around page, containing span pages
    (if possible). Page numbers run from 1 to last.

    &gt;&gt;&gt; list(page_range(2, 10))
    [1, 2, 3, 4, 5]
    &gt;&gt;&gt; list(page_range(4, 10))
    [2, 3, 4, 5, 6]
    &gt;&gt;&gt; list(page_range(9, 10))
    [6, 7, 8, 9, 10]

    """
    return range(max(min(page - (span - 1) // 2, last - span + 1), 1),
                 min(max(page + span // 2, span), last) + 1)