[Tutor] (no subject)

Alan Gauld alan.gauld at btinternet.com
Wed Jun 10 17:39:10 CEST 2015


On 10/06/15 11:36, rakesh sharma wrote:
>
> I have come across this syntax in python. Embedding for loop in []. How far can things be stretched using this [].
> l = [1, 2, 3, 4, 5]
> q = [i*2 for i in l]

This is a list comprehension which is a specific form of
the more generalised "generator expression":

<expression> for item in iterable if <condition>

And it is possible to have multiple loops and
complex expressions and conditions.

How far they can be taken is a good question.
They can be taken much further than they should be,
to the point where the code becomes both unreadable
and untestable.

Keep them relatively simple is the best advice.

There is no shame in unwrapping them to something
like:

aList = []
for item in anIterable:
     if condition:
        aList.append(expression)

If it is more maintainable and testable.
You can always wrap them up again later if it
is needed for performance reasons.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list