Minimum Code Prime List Generator (Python)

vegaseat 1 Tallied Votes 166 Views Share

Sometimes you want to accomplish something with a minimum ammount of code. Here is an example of using modern Python concepts of lambda, list comprehension and all() to create an anonymous function that returns a prime list from 2 to n.

# a minimum code prime list generator using lambda, nested
# list comprehensions and the new all() function from Python25
# tested with Python25       vegaseat       08jan2008

prime_list = lambda x:[i for i in range(2, x+1)\
    if all([i%x for x in range(2, int(i**0.5+1))])]

# test it for primes between 2 and 100 ...
print prime_list(100)

"""
my output -->
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""