# What is a list compression in Python?

Kit wkfung.eric at gmail.com
Tue Jan 19 01:26:31 CET 2010

```Oops...

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

On 1月19日, 上午8時24分, Kit <wkfung.e... at gmail.com> 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
>
> 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?
>
>
> > 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

```