[Tutor] confusing enumerate behavior

Alan Gauld alan.gauld at btinternet.com
Fri Feb 6 02:40:27 CET 2009


"Emad Nawfal (عماد نوفل)" <emadnawfal at gmail.com> wrote

> I'm a little, actually a lot confused by the behavior of the 
> enumerate

Its not enumerate thats confusing you its indexing.

> my_input = "one two three four five six seven eight nine ten"
> text = my_input.split()
> for i,v in enumerate(text):
>    line =  text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2],

for i=0 the first index is -3

but an index of -3 in Python is the third item
from the end. Its a little bit like the list was circular,
so, instead of falling off the end with -1, you wrap
around to the last item.

> ('eight', 'nine', 'ten', 'one', 'two', 'three', 'four')

So eight is text[-3] because its 3 from the end.

> I then though of adding dummy words

> text2 = " nothing " *6 + my_input + " nothing "* 6
> text2 = text2.split()
> for i,v in enumerate(text2[6:-6]):
>    line =  text2[i-3], text2[i-2], text2[i-1], v, text2[i+1], 
> text2[i+2],

by using the slice you extracted your old list and got the
same set of indexes! Instead of subtracting 3 you would
need to add six minus the offset:

line = text2[i+6-3], text2[i+6-2]....
by the way doesn't this look like it could be in a loop?

The other way is to simply test the index and if its beyond
the range of your list add 'nothing'. Something like:

my_input = "one two three four five six seven eight nine ten"
text = my_input.split()
for i,v in enumerate(text):
     for n in range(3,0,-1)
        if  i-n < 0:
          print 'nothing',
     print text[i],
     for n in range(1,4)
        if i+n >= len(text)
         print 'nothing,

Its late and this is untested but it should give a starting point.
My brain is saying something about list comprehensions
but I'm too tired to care :-)

Or another waty might be to use your text2 approach and
just print using indexes starting at the offset of your frst entry.
Actually that sounds like it might be the best way...

text2 = 'nil'*3+text+'niil*3
for i in range(3,len(text)):
    print text2[i-3:i+3]

or somesuch...

HTH

Alan G.
Zzzzzzzzzzzzzzzzzzzzzzzzzz....




More information about the Tutor mailing list