Python function to get numbers around another number I made a function to get a list with numbers around another number. Example: I want to get in a range of 2 numbers around 4. This will return: [2, 6]. You can set a min number and a max_number. That means when I set a min_num, the lower number should not be lower than the min number.

import sys


def get_numbers_around(number: int, min_num: int = None, max_num: int = None, _range: int = 2, on_fail_no_error: bool = False) -&gt; range:
    if max_num is None:
        max_num = sys.maxsize

    if min_num is None:
        min_num = -sys.maxsize - 1

    diff = max_num - min_num
    if diff &lt; _range:
        if not on_fail_no_error:
            raise ValueError(
                "Range is too small. Range is {0} big but difference between max_num and min_num is {1} big! ({0} &lt; {1}".format(
                    range, max_num - min_num))
        else:
            return range(number - diff, number + diff)

    final_list = [number - _range, number + _range]

    if final_list[0] &lt; min_num:
        diff = abs(min_num - final_list[0])
        final_list[0] = min_num
        final_list[1] += diff

    if final_list[1] &gt; max_num:
        diff = abs(final_list[1] - max_num)
        final_list[1] = max_num
        final_list[0] -= diff

    return range(final_list[0], final_list[1])


print(get_numbers_around(4)) # range(2, 6)
print(get_numbers_around(4, _range=5)) # range(-1, 9)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4, on_fail_no_error=True)) # range(-1, 1)
print(get_numbers_around(0, min_num=0, max_num=1, _range=4)) # ValueError


I think it is possible to optimize this code but I don't know how. Does anoyne have any idea?
Your code seems really complicated, and so you should follow KISS and YAGNI.
max_num and min_num don't work the way I would expect them to.
The error goes against what I think is Pythonic. Just return the smaller set.


def get_numbers_around(number, size):
    return range(number - size, number + size)


If you then need to implement min_num and max_num create a filter:

def filter_between(values, minimum=float('-inf'), maximum=float('inf')):
    return (v for v in values if minimum &lt;= v &lt;= maximum)




&gt;&gt;&gt; get_numbers_around(4, 5)
range(-1, 9)
&gt;&gt;&gt; list(filter_between(_, 0))
[0, 1, 2, 3, 4, 5, 6, 7, 8]