What is a list compression in Python?
python at mrabarnett.plus.com
Tue Jan 19 01:35:04 CET 2010
> 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