What is a list compression in Python?

MRAB python at mrabarnett.plus.com
Mon Jan 18 19:35:04 EST 2010


Kit wrote:
> Thank you so much guys.
> 
> Just out of curiosity: can I do something like this to "square all
> even numbers in the range 1-10"?
> print [x^2 for x in range (1,11) if x % 2 == 0]
> 
> Or is there a better way of doing it? Thanks for the help, and I am
> really appreciate your help.
> 
That would be:

     print [x ** 2 for x in range(1, 11) if x % 2 == 0]

Note that Python uses "**" for raising to a power and "^" (like in C)
for bitwise exclusive-or.



More information about the Python-list mailing list