Interesting talk on Python vs. Ruby and how he would like Python to have just a bit more syntactic flexibility.

Steve Howell showell30 at yahoo.com
Fri Feb 19 04:57:35 CET 2010


On Feb 18, 3:04 pm, "sjdevn... at yahoo.com" <sjdevn... at yahoo.com> wrote:
> On Feb 18, 11:15 am, Steve Howell <showel... at yahoo.com> wrote:
>
> >     def print_numbers()
> >         [1, 2, 3, 4, 5, 6].map { |n|
> >             [n * n, n * n * n]
> >         }.reject { |square, cube|
> >             square == 25 || cube == 64
> >         }.map { |square, cube|
> >             cube
> >         }.each { |n|
> >             puts n
> >         }
> >     end
>
> > IMHO there is no reason that I should have to name the content of each
> > of those four blocks of code, nor should I have to introduce the
> > "lambda" keyword.
>
> You could do it without intermediate names or lambdas in Python as:
> def print_numbers():
>     for i in [ cube for (square, cube) in
>                          [(n*n, n*n*n) for n in [1,2,3,4,5,6]]
>                if square!=25 and cube!=64 ]:
>         print i


The problem with list comprehensions is that they read kind of out of
order.  On line 2 you are doing the first operation, then on line 3
you are filtering, then on line 1 your are selecting, then on line 4
you are printing.

For such a small example, your code is still quite readable.

> But frankly, although there's no reason that you _have_ to name the
> content at each step, I find it a lot more readable if you do:
>
> def print_numbers():
>     tuples = [(n*n, n*n*n) for n in (1,2,3,4,5,6)]
>     filtered = [ cube for (square, cube) in tuples if square!=25 and
> cube!=64 ]
>     for f in filtered:
>         print f

The names you give to the intermediate results here are
terse--"tuples" and "filtered"--so your code reads nicely.

In a more real world example, the intermediate results would be
something like this:

   departments
   departments_in_new_york
   departments_in_new_york_not_on_bonus_cycle
   employees_in_departments_in_new_york_not_on_bonus_cycle
   names_of_employee_in_departments_in_new_york_not_on_bonus_cycle




More information about the Python-list mailing list