Discussion:
[Tutor] (no subject)
rakesh sharma
2015-06-10 10:36:23 UTC
Permalink
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]
print qthanksrakesh
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Joel Goldstick
2015-06-10 10:55:56 UTC
Permalink
On Wed, Jun 10, 2015 at 6:36 AM, rakesh sharma
Post by rakesh sharma
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]
print qthanksrakesh
This is called a list comprehension. They are a more concise way of
writing various for loops. You can google to learn much more
--
Joel Goldstick
http://joelgoldstick.com
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Alan Gauld
2015-06-10 15:39:10 UTC
Permalink
Post by rakesh sharma
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 - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Continue reading on narkive:
Loading...