[Tutor] Finding which list entry is being used, in a for loop (was: using -i flag with '''if __name__ == "__main__":'''
Terry Carroll
carroll at tjc.com
Fri May 20 00:17:08 CEST 2005
On Tue, 17 May 2005, Kent Johnson wrote:
> I often find that the information in the traceback and exception are
> enough to figure out the problem; if not, a few print statements can
> help. You will get better at this with experience.
Here's an example where traceback and print statements doesn't help, and
it's really nice to have access to the variables...
Suppose I have a long list of lists (by "long," I mean, too long to
display on one screen and visually examine easily), and am iterating over
the inner lists. (Forget whether there might be more
efficient ways;
this is just for illustration.)
In most languages, you'd take this unpythonic approach:
for i in range(0,len(mylist)):
for j in range(0, len(mylist[i])):
# stuff dependent on mylist[i][j]
I could put in "print i,j, mylist[i][j]" statements in here, and pretty
easily zero in on the exceptional data.
But a pythonic approach, and the one I find easiest, is:
for innerlist in mylist:
for item in innerlist:
# stuff dependent on item
Now, I can only put in "print item", and finding that in the nested list
is like a needle in a haystack. That's what I like about the -i
option... I can use Python expressions to iterate through the list
lookingfor stuff.
Is there any way, in the second construct, to have the traceback (or
equivalent info) include where in "innerlist" "item" came from, and where
in "mylist" "innerlist" came from?
More information about the Tutor
mailing list