Hi Tutors, I'm a little, actually a lot confused by the behavior of the enumerate function here. I have a text and I want to get each word within the context of the three preceding and the three following words. I tried this: #BEGIN 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], text[i+3] print line # END The ouput was not as I expected. It did not start from the beginning (actually I had expected it to throw and exception immediately) ('eight', 'nine', 'ten', 'one', 'two', 'three', 'four') ('nine', 'ten', 'one', 'two', 'three', 'four', 'five') ('ten', 'one', 'two', 'three', 'four', 'five', 'six') ('one', 'two', 'three', 'four', 'five', 'six', 'seven') ('two', 'three', 'four', 'five', 'six', 'seven', 'eight') ('three', 'four', 'five', 'six', 'seven', 'eight', 'nine') ('four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') Traceback (most recent call last): File "enumerate.py", line 13, in <module> line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], text[i+3] IndexError: list index out of range e...@emad-laptop:~/Desktop$
I then though of adding dummy words to the beginning and the end and exclude them later like this: #BEGIN my_input = "one two three four five six seven eight nine ten" 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], text2[i+3] print line #END The output this time was even more confusing: e...@emad-laptop:~/Desktop$ python enumerate.py ('nothing', 'nothing', 'nothing', 'one', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'two', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'three', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'four', 'nothing', 'nothing', 'one') ('nothing', 'nothing', 'nothing', 'five', 'nothing', 'one', 'two') ('nothing', 'nothing', 'nothing', 'six', 'one', 'two', 'three') ('nothing', 'nothing', 'nothing', 'seven', 'two', 'three', 'four') ('nothing', 'nothing', 'one', 'eight', 'three', 'four', 'five') ('nothing', 'one', 'two', 'nine', 'four', 'five', 'six') ('one', 'two', 'three', 'ten', 'five', 'six', 'seven') Can somebody please explain what is going on here? Have I done something wrong? How can this be fixed? Thanks in anticipation, Emad
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor