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

Kent Johnson kent37 at tds.net
Sun Feb 15 18:09:52 CET 2009


On Sun, Feb 15, 2009 at 9:16 AM, Wayne Watson
<sierra_mtnview at sbcglobal.net> wrote:

> 3. Where can I find out more about enumerate, as used here:
>
> input_file=open('Initial.sen','r')
> for (line_cnt, each_line) in enumerate(input_file):
>     print each_line
> input_file.close()
>
> I used this small program for other purposes in the distant past, but what's
> going here with enumerate? Documentation for enumerate seems scarce.

The official docs are here:
http://docs.python.org/library/functions.html#enumerate

It's pretty simple, perhaps that is why not a lot is written about it.

When you iterate a sequence with a for loop, you get just the elements
in the sequence:
In [18]: seasons = ['Spring', 'Summer', 'Fall', 'Winter']

In [19]: for season in seasons:
   ....:     print season

Spring
Summer
Fall
Winter

Sometimes it is useful to also get the index of the element, not just
the element. That is when you use enumerate:

In [20]: for i, season in enumerate(seasons):
   ....:     print i, season

0 Spring
1 Summer
2 Fall
3 Winter

Technically, the result of calling enumerate() is a sequence whose
elements are pairs (tuples) of (index, item). Using tuple assignment
you can easily assign these to two variables, as above. This is the
most common use. You can also use enumerate() without unpacking the
tuples, maybe this makes it a little clearer what is happening:

In [22]: for item in enumerate(seasons):
    print item

(0, 'Spring')
(1, 'Summer')
(2, 'Fall')
(3, 'Winter')

Kent


More information about the Tutor mailing list