[Tutor] how does this list comprehension work?

Anna Ravenscroft annaraven at gmail.com
Thu Mar 9 00:57:27 CET 2006


On 3/8/06, Christopher Spears <cspears2002 at yahoo.com> wrote:
>
> I copied this program from Learning Python and got it
> to work on Windows XP:
>
> import sys, glob
> print sys.argv[1:]
> sys.argv = [item for arg in sys.argv for item in
> glob.glob(arg)]
> print sys.argv[1:]
>
> What the program does is first print the glob and then
> a list of everything caught by the glob.  For example:
>
> ['*.py']
> ['showglob.py']
>
> The key to the script is the list comprehension, which
> I am having trouble dissecting.  How do I go about
> trying to figure out how it works?



Hi Christopher,

Others have ably deciphered this particular list comprehension (LC) for you.
I'm curious though, are you having trouble because this is a nested list
comprehension or do you not have a good grasp on LCs in general? They can be
a little tricky to grok at first.

In case you're not completely clear on LCs in general, here's a bit more
description. If you are clear, just skip to the next email. ;-)


First off - a list comprehension creates a new list. It does so by pulling
items from an existing list or other iterable object.  So, for example:

newlist = [item for item in oldlist]
print newlist

This example wasn't terribly useful - it just made a new list. You can,
however, *do* stuff to the item as you're passing it to the new list. For
example, if you want the squares of the items in the old list, you coudl do:

oldlist = [1,2,3]
sqlist = [item*item for item in oldlist]


Another thing you can do is filter the items in the old list in some way.
So, if you only want the even numbers you could do:

elist = [item for item in oldlist if item%2==0] # using modulo, which
returns the remainder

You can use LCs with files, with dicts, with strings, with any iterable
object. It's really slick, really easy, pretty fast.  LCs can be a little
tricky, like I mentioned (especially when nested) but are quite handy and
fun once you get to know them. Just don't get so tricky that it's hard to
read your code. If it's getting hard to read, use a for loop.

HTH,
Anna
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060308/90489047/attachment.html 


More information about the Tutor mailing list