What is a list compression in Python?

Kit wkfung.eric at gmail.com
Mon Jan 18 19:24:11 EST 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.

Kit.

On 1月19日, 上午12時30分, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Mon, 18 Jan 2010 08:07:41 -0800, Kit wrote:
> > Hello Everyone, I am not sure if I have posted this question in a
> > correct board. Can anyone please teach me:
>
> > What is a list compression in Python?
>
> Google "python list comprehension".
>
> If Google is broken for you, try Yahoo, or any other search engine.
>
> > Would you mind give me some list compression examples?
>
> Instead of this:
>
> L = []
> for x in range(10):
>     L.append(x**2)
>
> you can write:
>
> L = [x**2 for x in range(10)]
>
> Instead of this example:
>
> L = []
> for x in range(10):
>     if x % 2 == 0:
>         L.append(x**2)
>
> you can write:
>
> L = [x**2 for x in range(10) if x % 2 == 0]
>
> --
> Steven




More information about the Python-list mailing list