Problem inserting a value from one list to another if that value is a prime number

Viewed 42

I'm trying to add only the prime numbers from my first list into a second list.

I'm not receiving any output.

li1= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
li2=[]

def is_primeList(lst):
    pos = 2
    for i in range(len(lst)):
        x = True
    if(i<2):
        x = False
        for j in range(2, i):
            if i% j == 0:
                x = False
                break
        if x:
            li2.insert(i + pos, li1[i])
        else:
            print("Not prime")

is_primeList(li1)

for element in li2:
    print(element)

3 Answers

It returns:

li1= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
li2=[]

def is_primeList(lst):
    pos = 2
    for i in range(len(lst)):
        x = True
        if(i<2):
            x = False
        else:
            for j in range(2, i):
                if i% j == 0:
                    x = False
                    break
        if x:
            li2.insert(i + pos, li1[i])
        else:
            print("Not prime")

is_primeList(li1)

for element in li2:
    print(element)

In your code the if statement is outside the for so it will never execute in the proper way, kindly indent the code right

li1= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
_prime_list = li1[2:3]


def is_primeList():
    for _i in li1[3:]:
        # print _i,
        _is_prime = [_i % _n == 0 for _n in _prime_list]
        # print _is_prime
        if not any(_is_prime):
            _prime_list.append(_i)

is_primeList()
print _prime_list

Outputs

[2, 3, 5, 7, 11, 13, 17, 19]

You have bugs in your code. Please use this example as a starting point

Related