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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor