Optimization of list's sublist
You can streamline by dropping the use of append, and ignoring values in your for-loop that are automatically disqualified.  Benchmarking shows these steps reduce execution time by about 2x.

Original:

%%timeit

origin=[2,0,11,3,0]
left=1
right=10
query(origin,left,right) 
# 3.6 µs ± 950 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


New version:

def query2(sliced,left,right):
    count = 0
    leng = len(sliced)
    for i in range(leng):
        if sliced[i] &lt;= right:
            stack_ct = 0
            end_index = i
            found_max = False
            while(end_index &lt; leng and sliced[end_index] &lt;= right):
                if not found_max:
                    found_max = sliced[end_index] &gt;= left
                end_index += 1
                stack_ct += 1
            if found_max:
                count += stack_ct
    return count


Benchmarking:

%%timeit

origin=[2,0,11,3,0]
left=1
right=10
query2(origin,left,right)
# 1.83 µs ± 41.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)