What is a list compression in Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Jan 18 17:30:22 CET 2010


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