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


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to