How to find specific elements in a list and combine them into a new list (Python3)

First of all, I’m new to this site and to programming so if my level of writing code is bad or the way I ask my question is wrong, please point me into the right direction.

I’ve written a program in Python3 which enables me to get a list of all primes numbers less of equal than a given number N of my choosing. If my input is 10 for instance, my programm will give the following result:

[2, 3, 5, 7]

Now I’m trying to write a follow-up programm which gives me number of twinprimes for a given number N. So for instance: if N = 10, I know there are two twinprimes [3,5] and [5,7]. I tried the following:

def twinprimes(n):
    x = primes(n)
    ps = [] 
    for i in range(len(x)):
        if x[i]+2==x[i]:
    return ps

So I’m trying to make a new list ps in which all the first values of the twinprime pair are added so that I can find len(ps) to find the total value of twinprimes.

Now I know there is a lot wrong with my code. I just don’t know how to make it work.


You are trying to test if a prime number is equal to itself plus 2:

if x[i]+2==x[i]:

No number can ever be equal to itself plus a non-zero other number, so that test is never going to pass.

You want to test if the current prime number is 2 less than the next number in your list:

if x[i] == x[i + 1] - 2:  # two adjacent primes differ by 2

This will run into issues with i + 1 not being a valid index into x however, because you loop up to (but not including) len(x); len(x) + 1 is going to rais an IndexError. But you don’t need to test the last prime number anyway, so the following would work:

for i in range(len(x) - 1):
    if x[i]  == x[i + 1] - 2:
        ps.append((x[i], x[i + 1]))

This adds both primes.

There are more pythonic ways of producing this list; pairing up the prime numbers with zip() for example, and using a list comprehension:

def twinprimes(n):
    x = primes(n)
    return [(a, b) for a, b in zip(x, x[1:]) if a == b - 2]

Leave a Reply

Your email address will not be published. Required fields are marked *