python quirk with nested for loops


20-07-2006 21:20:42

hey, i'm getting a really strange error with python, using 2.4.

it's easily reproduced if you type the following into the interpreter:

for k in range(2):
for i in range(2):
print j[i]

For some reason i get a TypeError: unsubscriptable object error on the print j when I do this, and I just don't get why! Anyone else ever run into this before?

ps Sorry, I know this isn't really a general python forum, but I thought it'd be out of place in the 'Back to Basics' as it's not really C++ and I don't really frequent any propper python forums (if anyone can suggest one that's active and likely to be able to answer these sorts of questions, that'd be awesome as well)


20-07-2006 21:56:47

Works for me (Python 2.4.3).

>>> j=[5,6]
>>> for k in range(2):
for i in range(2):
print j[i]



20-07-2006 22:07:33

Also works for me (Python 2.4.3), same output as OvermindDL1.


21-07-2006 14:09:29

That unscriptable object error means that j is defined as something other than a list, but it IS defined (otherwise you'd get a not defined error). I'd look for a typo on either line 1 or 4.

Add "print type(j)" just before "print j" and see what it says.