Creating a page number array for pagination I have written a small function to generate an array of page numbers for displaying a pagination. The inputs to the function is an active page number p, and the max page number. The function will return an array of 5 possible page numbers available near the active page. 

Example input, output:

pages(1,10): [1,2,3,4,5]

pages(10,10): [6,7,8,9,10]

pages(5,10): [3,4,5,6,7]


The function is:

def pages(p,max):
    a=[p]
    while len(a)&lt;5 and not (a[0]==1 and a[-1]==max):
        if a[0]&gt;1:
            a.insert(0,a[0]-1)
        if a[-1]&lt;max:
            a.append(a[-1]+1)
    return a


Is there anything to do to improve this code, or is there any other simpler methods to achieve this?
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)