How to rewrite this as list comprehension?
Paul Moore
paul.moore at uk.origin-it.com
Tue Dec 19 08:06:17 EST 2000
On Tue, 19 Dec 2000 13:07:49 +0100, "Serge Beaumont"
<serge at sergebeaumont.com> wrote:
>Hello,
>
>I'm trying to get my head around comprehensions. How would I rewrite this
>method?
>
> def deadThings(self, type = None):
> deadThings = self.destroyed[:]
> for thing in self.things:
> if thing.destroyed:
> if type:
> if isinstance(thing, type):
> deadThings.append(thing)
> else:
> deadThings.append(thing)
> return deadThings
I think it goes:
deadThings = self.destroyed[:]
deadThings += [x for x in self.things
if (x.destroyed and
(not type or isinstance(x, type)))]
Start from the inside and work out. The nasty (not type or ...) bit is
a translation of the "if type: if isinstance(): else:" bit into an
expression as opposed to a statement. In C I might have written
(type ? isinstance() : true)
but I'm not sure it's much clearer.
Whether you find the list comprehension clearer is a matter of taste.
Just because it exists, doesn't mean it is the right answer in all
cases...
Paul
More information about the Python-list
mailing list