[Tutor] how does this list comprehension work?
Kent Johnson
kent37 at tds.net
Wed Mar 8 19:32:31 CET 2006
Christopher Spears 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?
A list comprehension is a shortcut for a series of one or more nested
for loops and if statements with a list append in the middle of it.
The list comp pulls the value to be appended out of the loops but
otherwise the order is not affected. Looking at
[item for arg in sys.argv for item in glob.glob(arg)]
item is the thing that will be appended to the list. The nested for
loops are
for arg in sys.argv:
for item in glob.glob(arg):
If you initialize a list outside the loop, and append to it inside the
loop, you have the equivalent loops:
vals = []
for arg in sys.argv:
for item in glob.glob(arg):
vals.append(item)
Kent
More information about the Tutor
mailing list