ALL Python Programmers Should Know This!!
This is a powerful tip that all Python programmers should know.
So here I have a list of numbers from one to one thousand:
nums = range(1,1000)
print(list(nums))
But what I want to do is to get all the prime numbers in that list.
So what I will do first, is create a function called is_prime
which takes in a single number and returns false if the number is not prime and returns true if it is:
nums = range(1,1000)
print(list(nums))
def is_prime(num):
for x in range(2, num):
if (num % x) == 0:
return False
return True
And now all I have to do is use Python’s built-in filter()
function.
I’ll add is_prime
and the nums
as inputs:
nums = range(1,1000)
print(list(nums))
def is_prime(num):
for x in range(2, num):
if (num % x) == 0:
return False
return True
primes=filter(is_prime, nums)
Essentially what this does is applies the is_primes
function to every item in the nums
list.
If a boolean True
is returned, it stores it in our primes
variable otherwise, it removes the number.
All we have to do now is print our primes
variable however you will see it prints out a filter object.
This is Python’s way of conserving memory and so we need to convert it into a list by putting primes
inside of a list
function and now we can run:
nums = range(1,1000)
print(list(nums))
def is_prime(num):
for x in range(2, num):
if (num % x) == 0:
return False
return True
primes=filter(is_prime, nums)
print(list(primes))