Some "pythonic" suggestions for Python

Bruno Desthuilliers bdesth.quelquechose at
Thu Nov 8 23:30:57 CET 2007

Frank Samuelson a écrit :
> I love Python, and it is one of my 2 favorite
> languages.  I would suggest that Python steal some
> aspects of the S language.
> -------------------------------------------------------
> 1. Currently in Python
> def  foo(x,y): ...
> assigns the name foo to a function object.  Is this pythonic?

Yes. Python deliberately choosed to be a statement-based language.

> Why not use the = operator like most other assignments?

This dead horse has been beaten to hell and back.

Note that as far as I'm concerned, I may like an expression-based 
Python-inspired language. But this is another story.

> -------------------------------------------------------
> 2. Allow sequences to be indices:
>  >>> s=["hello", 6, 33, "none"]
>  >>> x= [1,3]
>  >>> [ s[y] for y in x]     # Current verbose version

Verbose ???

> [6, 'none']
>  >>> s[x]                   # Simpler, clearer, more productive
> To quote a poster at,
> "While we are at it, I also don't understand why sequences can't be
> used as indices. Why not, say, l[[2,3]] or l[(2, 3)]? Why a special
> slice concept? 

slices are very powerful.

>"  Isn't that unpythonic?

Not IMHO. But extending slices to support might not be totally stupid. 
Do you volunteer to write the PEP and the patch ?

> --------------------------------------------------------
> 3. When I first started using python, I frequently used
> map, because I didn't want to have to learn the
> additional syntax of list comprehensions, which
> appeared very nonstructured.
> # Is this readable?
> b= [x+y for x in vec1 if x>0 for y in vec2 if y>x ]


> Perhaps a list comprehension syntax more like the rest
> of python. "for" could return a list given by continue
> arguments:
> b= for x in vec1 :
>       if (x>0):  continue     # "returns" nothing
>       continue for y in vec2:
>          if (x>y): continue(x+y)

Now *this* is a mess. And FWIW, you inverted the second test...

> Note that my code would actually return a list of lists
> rather than a single list like the list comprehension.
> More structured syntax opens the door to having much
> more complicated, yet still comprehensible (thus more
> pythonic), list comprehensions.

The Pythonic way to write "more complicated yet still comprehensible 
list comprehensions" is to not use list comprehensions.

b = []
for x in vec1:
   if x > 0:
     for y in vec2:
       if y > x:
         b.append(x + y)

Or if you really want a more functional approach:

def do_stuff(vec1, vec2):
   for x in vec1:
     if x > 0:
       for y in vec2:
         if y > x:
           yield x + y

b = list(do_stuff(vec1, vec2))

More information about the Python-list mailing list