What is a list compression in Python?

Stephen Hansen apt.shansen at gmail.com
Mon Jan 18 11:25:24 EST 2010


On Mon, Jan 18, 2010 at 8:07 AM, Kit <wkfung.eric at gmail.com> 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?
>
> Would you mind give me some list compression examples?
>

Do you mean list *comprehension*? If so, its a special syntax for list
construct which can be used for shorter, clearer code (provided one doesn't
abuse it, at which point it becomes quite obtuse). Its never required:
nothing you do with a list comprehension you couldn't do with a standard
loop.

For example:

evens = []
for n in range(100):
    if n %2 == 0:
        evens.append(n)

verses:

my_list = [n for n in range(100) if n % 2 == 0]

The basic syntax is:

[<expression that is appended> for <name> in <iterable>]

The 'if' part at the end is optional. The syntax is converted into a for
loop that builds a list, and then returns it to you.

So, basically it becomes:

temp = []
for <name> in <iterable>:
    temp.append(<expression that is appended>)

Except the 'temp' variable doesn't really have  a name and is returned from
the comprehension, where you can give it a name. Sometimes you need an 'if'
clause, sometimes you don't. Sometimes your 'expression to be appended' is
very simple, other times you mutate it. For example, an easy way to convert
a list of numbers into a list of strings is:

[str(x) for x in range(10)]

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20100118/2e92ef12/attachment.html>


More information about the Python-list mailing list