Finding the first pair of prime numbers that have some specified difference I tried printing the first pair of prime number in between a list of numbers with a particular difference. But my run time is still too high (for large range of numbers). I want to reduce the run time by using any method from standard library like itertools.
def prime(x):
    &quot;&quot;&quot;To generate prime number&quot;&quot;&quot;
    a = x // 2 + 1
    for i in range(2, x):
        if x % i == 0:
            return False
        elif i == a:
            return True


def gap(p, q, m):
    &quot;&quot;&quot;To generate gap in between two prime numbers&quot;&quot;&quot;
&quot;&quot;&quot;p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit&quot;&quot;&quot;
    b = []
    a = b.append
    c = prime
    q = (q // 2) * 2 + 1
    for i in range(q, m + 1, 2):
        if c(i) == True:
            a(i)
            if len(b) &gt; 1:
                if b[-1] - b[-2] == p:
                    return [b[-2], b[-1]]
First thing first, get rid of these ugly a and c. They do not add any value, but only obfuscate the code.
def gap(p, q, m):
    &quot;&quot;&quot;To generate gap in between two prime numbers&quot;&quot;&quot;
&quot;&quot;&quot;p is the difference,q is the lower limit where the list of numbers in between which prime is filtered,m is the upper limit&quot;&quot;&quot;
    b = []
    q = (q // 2) * 2 + 1
    for i in range(q, m + 1, 2):
        if prime(i):
            b.append(i)
            if len(b) &gt; 1:
                if b[-1] - b[-2] == p:
                    return [b[-2], b[-1]]

Notice that I also removed a redundant == True.
Second, you don't need to keep the entire list of primes. You are only interested in the last two of them. Consider
def gap(p, q, m):
    b = find_first_prime_after(q)
    for i in range(b + 2, m + 1, 2):
        if prime(i):
            if i - b == p:
                return b, i
            b = i

Finally, your primality test is very suboptimal. Implementing the sieve would give you a boost.