[Tutor] What is this [] construction?

Andre Engels andreengels at gmail.com
Tue Mar 3 08:18:56 CET 2009


On Tue, Mar 3, 2009 at 4:54 AM, Wayne Watson
<sierra_mtnview at sbcglobal.net> wrote:
> What is this: d = [ int(x) for x in s.split(":") ]
> I see in the program I'm looking at, the [] construction can be much more
> complicated, as in:
>        self.recent_events = [ event for event in self.recent_events
>                                if os.path.exists(event) and
>                                (time.time() - os.path.getmtime(event)) <
> 3600.0 ]

That's called list comprehension. The notation
[f(x) for x in A if p(x)]
means:
Form a list in the following way:
Start with an empty list. Then go through A, and for each x in A, if
p(x) is true, add f(x) to the list.

d = [f(x) for x in A if p(x)]

is equivalent to:

d = []
for x in A:
    if p(x):
        d.append(f(x))

Your first example had no p(x) defined, which means that it's done for
all x, that is:

[ int(x) for x in s.split(":") ]

means:

The list, formed by taking int(x) for all x in the result of s.split(":").

It is almost English, really...

[f(x) for x in A if p(x)]

means:

f(x) for all x in A for which p(x) holds.

-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list