[Tutor] Question on List Comprehensions

Charles Karl Becker charleshbecker at gmail.com
Tue Nov 22 06:45:25 CET 2011


Steven and Alan,

Thank you for your comments!

Alan said:
>> 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:

This helps me understand a lot when looking back, I thought that any
operation done in place of defining the list literally was a list
comprehension.  I'm on wikipedia and a few tutorials now to refine and
will post back when I've come up with the solution I'm looking for
(and a comment as to if it's worth replacing a for loop with).

Thanks again!
Charles

On Mon, Nov 21, 2011 at 7:04 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 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/
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list