Using += in a loop

Carl Banks imbosol at vt.edu
Thu Aug 8 18:02:19 EDT 2002


Bill Dandreta wrote:
> All we need now is predecessor and successor functions (like Pascal
> has). I find my self wanting to use the previous and/or next element
> in a sequence sometime when looping through.


We already have it:


Python 2.1.3 (#1, Apr 20 2002, 10:14:34) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5]
>>> for item,prev,next in zip(a,[None]+a[:-1],a[1:]+[None]):
...     print "Item:",item,"   Previous:",prev,"   Next:",next
... 
Item: 1    Previous: None    Next: 2
Item: 2    Previous: 1    Next: 3
Item: 3    Previous: 2    Next: 4
Item: 4    Previous: 3    Next: 5
Item: 5    Previous: 4    Next: None


If you need this a lot, you can write a function to encapsulate the
zip.


-- 
CARL BANKS
http://www.aerojockey.com



More information about the Python-list mailing list