Extract elements of a list meeting a specific condition.

I’m trying to make a list of numbers that are twin primes. I wrote a function to check if a number is a twin prime or not.

Attributes[twinPrimeQ] = {Listable};

twinPrimeQ[n_] := 
 PrimeQ[n] && 
  n > 2 && (NextPrime[n] - n == 2  || n - NextPrime[n, -1] == 2)

How can I apply that to a list of integers, to pick out the twin primes, which will hopefully be those at
A001097 - OEIS ?

I thought something like this would work

In[19]:= Table[n, {n, 0, 20}]  /; twinPrimeQ[n]

Out[19]= {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 
  17, 18, 19, 20} /; twinPrimeQ[n]

but it obviously does not work as I intended.

Hi David,

One way

Table[n, {n, 0, 20}] // Select[twinPrimeQ]

Listable allows this

Table[n, {n, 0, 20}] // twinPrimeQ

This is about 3x faster

twinPrime2Q[n_] := PrimeQ[n] && (PrimeQ[n + 2] || PrimeQ[n - 2])

<< GeneralUtilities`
BenchmarkPlot[{twinPrimeQ, twinPrime2Q}, Range[#] &, 10^Range[6], "IncludeFits" -> True]

Thank you for your help.

Dave