[Tutor] construct
Kent Johnson
kent37 at tds.net
Fri Nov 4 19:53:41 CET 2005
Eric Walker wrote:
> All,
> Whats the construct that allows to loop through a list and perform an action?
> you also can add a test at the end. something like myfile = [print name for
> name in yourlist, if ...]
It's called a list comprehension. You can see some examples here:
http://docs.python.org/tut/node7.html#SECTION007140000000000000000
It won't work with your example though - 'print' is a statement, not an expression, and cannot be used in a LC. You could use sys.stdout.write(name + '\n') instead if you like.
Personally I think it is bad style to use a LC for its side effects; in those cases I prefer to write the loop out.
Kent
--
http://www.kentsjohnson.com
More information about the Tutor
mailing list