Request a short code review
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sun Apr 20 04:12:24 EDT 2008
En Fri, 18 Apr 2008 15:10:09 -0300, <james at reggieband.com> escribió:
> lessons = self.lesson_data["lessons"]
> if lesson_type:
> lessons = [x for x in lessons if x["type"] == lesson_type]
>
> Changes:
> - generator expression instead of filter
The above is not a generator expression, it's a list comprehension. They look similar.
This is a list comprehension:
py> a = [x for x in range(10) if x % 2 == 0]
py> a
[0, 2, 4, 6, 8]
Note that it uses [] and returns a list. This is a generator expression:
py> g = (x for x in range(10) if x % 2 == 0)
py> g
<generator object at 0x00A3D580>
py> g.next()
0
py> g.next()
2
py> for item in g:
... print item
...
4
6
8
Note that it uses () and returns a generator object. The generator is a block of code that runs lazily, only when the next item is requested. A list is limited by the available memory, a generator may yield infinite items.
> Cheers again. This is very valuable for me. I am a true believer
> that if one takes care in the smallest of methods then the larger code-
> base will be all the better.
Sure.
--
Gabriel Genellina
More information about the Python-list
mailing list