What is a list compression in Python?

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Jan 18 22:49:37 EST 2010


On Mon, 18 Jan 2010 16:24:11 -0800, 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]

^ is the XOR operator in Python. You want:


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

or even better:

[x**2 for x in range (2, 11, 2)]




-- 
Steven



More information about the Python-list mailing list