Inserting while itterating

Mike C. Fletcher mcfletch at rogers.com
Wed Jan 14 10:04:31 CET 2004


Thomas Guettler wrote:

>Hi,
>
>Simple excerise:
>
>You have a sorted list of integers:
>l=[1, 2, 4, 7, 8, 12]
>
>and you should fill all gaps:
>
>result == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>  
>
Well, here's the simplest one...
    if l:
        l[:] = range(l[0],l[-1])

but what you're probably looking for is (untested):

for x in range( len(l)-2, -1, -1 ):
    if l[x+1] != l[x]+1:
       l[x+1:x+1] = range(l[x]+1,l[x+1])

Enjoy,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/







More information about the Python-list mailing list