pythonpython-3.xlistremove-method

how to remove composite numbers from a list in python 3?


I am not able to remove composite numbers from a list in python 3 .Can you help?

Example input:

list1 = [2, 3, 6, 7, 14, 21, 23, 42, 46, 69, 138, 161, 322, 483]

Expected output:

list1 = [2, 3, 7, 23]

Thanks in advance.


Solution

  • You can use a list comprehension with all:

    list1 = [2, 3, 6, 7, 14, 21, 23, 42, 46, 69, 138, 161, 322, 483]
    new_result = [i for i in list1 if all(i%c != 0 for c in range(2, i))]
    

    Output:

    [2, 3, 7, 23]