[Tutor] Question on List Comprehensions

Alan Gauld alan.gauld at btinternet.com
Tue Nov 22 03:04:14 CET 2011


On 22/11/11 00:10, Steven D'Aprano wrote:

> Because you don't have a list comprehension. You can't put add arbitrary
> code inside a square brackets [ ]. You have to follow the syntax for a
> list comprehension:
>
> listcomp = [expression for name in sequence]
>
> not
>
> listcomp = [expression for name in sequence another_command]

And being picky you can add a conditional after the loop:

 > listcomp = [expression for name in sequence if some_condition]

But it must be an if test, nothing else will do.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list