Python style.
Jarkko Torppa
torppa at polykoira.megabaud.fi
Wed May 10 07:40:46 EDT 2000
In article <391914DD.BF2A2C32 at ecs.soton.ac.uk>, 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.
It would be more elegant to build your lists as list of tuples
l = [ ( 1,6 ), (2,5), (3,4), (4,3), (5,2), (6,1) ]
for e in l:
print e[0] - e[1]
but if that is not possible, this looks a bit nicer
list1 = [ 1,2,3,4,5,6 ]
list2 = [ 6,5,4,3,2,1 ]
for i in range(0,len(list1)):
print list1[i] - list2[i]
More information about the Python-list
mailing list