Python style.

Gareth McCaughan Gareth.McCaughan at pobox.com
Wed May 10 16:24:16 EDT 2000


Fredrik Lundh wrote:

> Jacek Generowicz <jmg at ecs.soton.ac.uk> wrote:
>> How would you rewrite the following code, in good
>> python style ?
>> 
>> list1 = [ 1,2,3,4,5,6 ]
>> list2 = [ 6,5,4,3,2,1 ]
>> 
>> count = 0
>> for item in list1:
>>     print item - list2[count]
>>     count = count + 1
> 
> slightly less obscure:
> 
>     for i in range(len(list1)):
>         item1 = list1[i]
>         item2 = list2[i]
>         ...
> 
> the slightly more obscure way:
> 
>     for item1, item2 in map(None, list1, list2):
>         ...

For this particular case, I suggest

    for x in map(lambda a,b: a-b,
                 list1,list2):
      print x

or, for those who aren't scared of such things,

    for x in map(operator.sub, list1,list2):
      print x

Of course this only works because the operation being
done on the items factors into (1) a simple combination
of the two, and (2) something being done to the result.

I can't persuade myself not to remark on how much I
hate the way that Python's syntax for lambdas and map/reduce
interacts to produce horrors like

    map(lambda a, b, c: a+b+c, p, q, r)

But my preference, which is for some notation along the
lines of

    map({a,b,c -> a+b+c}, p,q,r)

isn't very Pythonic. Especially as we already have a {...}
syntax for dictionaries.

(I admit to slightly disingenuous use of whitespace in the
last two snippets.)

Best of all for this, of course, would be list comprehensions.
But that's been done to death in c.l.py already.

-- 
Gareth McCaughan  Gareth.McCaughan at pobox.com
sig under construction



More information about the Python-list mailing list