[Python-Dev] list comprehensions again...

Paul Prescod paul@prescod.net
Wed, 12 Jul 2000 04:25:33 -0500

"Barry A. Warsaw" wrote:
> [Python is becoming Perl]

>     | print [i, s for i in nums for s in strs]

Let me try my syntax on this example:

print [for i in nums:
	 for s in strs:
		i, s]

I don't see that as being any worse than the procedural syntax.

>  | print [i, s for i in nums for s in [f for f in strs if "n" in f]]

I don't see this as being a realistic example.

First, let me ask whether you think that reasonable programmers are
actually going to come up with this. Why wouldn't they use a temporary
variable for s? When nesting gets deep, reasonable programmers try to
unroll it, whether it is in a.b.c.d.e or a(b(c(d(e())))) or list comps.

In fact, we know that most UNreasonable programmers can be swayed with
arguments from efficiency. You are computing the value of s over and
over again "num" times. It makes no sense to do it that way. I think
that my syntax would make this clearer (of course I would!):

print [
	for i in nums:
		 for s in [for f in strs:
				 if "n" in f:

You can see that nothing from the outer loop is being used in the inner
one, so what's the point in having it there? Better:

s=[for f in strs:
	 if "n" in f:

print [for i in nums:

Which to me is a nicer way of saying what we today say as:

map( None, nums, [s]*len(nums)]

If you want to confuse a newbie, I'll claim that the "map" version will
do it more than the list comp. version.

 Paul Prescod - Not encumbered by corporate consensus
Simplicity does not precede complexity, but follows it. 
	- http://www.cs.yale.edu/~perlis-alan/quotes.html