Welcome, guest | Sign In | My Account | Store | Cart

Get the primes from 1 to 100 or really any range you choose.

Python, 1 line
print [i+2 for i, numberList in enumerate([[i for x in range(2, i+1) if i % x == 0 and i != x] for i in range(2,100)]) if not numberList]


Colin Fotheringham 14 years, 4 months ago  # | flag

I'm pretty new to Python and don't pretend to begin to understand this code.

I thought the idea of these recipes was to provide instruction or enlightenment. This seems to be an attempt to cram as much code into one line as possible in the hope of impressing someone. I'm sorry if that wasn't the intention; it's certainly the impression.

I was led to believe that Python was noted for its clarity and readability; I guess obfuscation is possible in any language :-)

Could anybody add a comment or two to this code that sheds some light on how it works ?



Milo Zou 14 years, 4 months ago  # | flag

I think the enumerate() is not necessary here at all. We could get what we want by

print [i for i in range(2, 100) if not [x for x in range(2, i) if i % x == 0]]

more clearly. of course, in fact we used the same method.

Colin Fotheringham 14 years, 4 months ago  # | flag

That's certainly a lot shorter, cleaner and clearer !

Created by Adam M Prost on Fri, 13 Nov 2009 (MIT)
Python recipes (4591)
Adam M Prost's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks