[Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate

Alan Gauld alan.gauld at btinternet.com
Sun Feb 15 23:41:31 CET 2009


"Wayne Watson" <sierra_mtnview at sbcglobal.net> wrote
> I'm still looking for an explanation of "
> for (line_cnt, each_line) in enumerate(input_file)".
> Why the tuple?
> Apparently, line_count gets a line number, and each_line gets the 
> string

OK, Back up from the specific problem to the more general case.

enumerate does not return the line number it returns the
current index of the collection:

for index, item in [9,8,7,6]:
   print index, item


0 9
1 8
2 7
3 6

If you are familiar with list comprehensions (or generator 
expressions)
you could do the same yourself with:

>>> lst = [9,8,7,6]
>>> for i,n in ((i,lst[i]) for i in range(len(lst))):
...     print i, n
...
0 9
1 8
2 7
3 6
>>>

But enumerate is easier on the eye.

And if its the i,n bit that confuses that is just tuple unpacking.
We can do this:

>>> a,b = (1,2)
>>> print a, b
1 2

Now, coming back to your specific case.
The index of a file "collection" is the line number (starting at
zero of course) and the item is the line of text.

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list