[Tutor] What is this [] construction?

Marc Tompkins marc.tompkins at gmail.com
Tue Mar 3 09:26:30 CET 2009

On Mon, Mar 2, 2009 at 11:18 PM, Andre Engels <andreengels at gmail.com> wrote:

> On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson
> <sierra_mtnview at sbcglobal.net> wrote:
> >        self.recent_events = [ event for event in self.recent_events
> >                                if os.path.exists(event) and
> >                                (time.time() - os.path.getmtime(event)) <
> > 3600.0 ]

In this example, we'll step through self.recent_events - which apparently is
a list of filenames - and call each item we come across "event".  That's the
"for event in self.recent_events" part.
If the filename corresponds to an actual file ("if os.path.exists(event)")
AND that file has been modified less than an hour ago (the difference
between the current time and the file's modification time is less than 3,600
seconds), then we add "event" to the list we're building and move on to the
next "event" until we're done.
At the end, we call our new list self.recent_events, which replaces the list
we were looping through a moment ago.  Chances are it's a bit shorter now.

List comprehensions will make your head hurt the first few dozen times you
encounter them.  After that, they become easier to use than the longer
for-loop structure they replace - as André pointed out, they read almost
like English.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090303/e296d871/attachment.htm>

More information about the Tutor mailing list