Python style.

Chuck Esterbrook echuck at mindspring.com
Wed May 10 14:17:15 EDT 2000


Jacek Generowicz 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
> 
> In other words, I want to loop through two lists,
> performing some operation on elements in
> corresponding positions . . . there must be a more
> elegant way.
> 
> Thanks,
> 
> Jacek


I'm surprised I haven't seen this version, yet:


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


That doesn't feel obscure to me and in most of my programs I'm passing my results around more often than I'm directly dumping them to the console (where they're no longer usable). The point is I would probably "return" the map() above or stick in a var, except for really simple programs.

-Chuck



More information about the Python-list mailing list