[Tutor] Readlines

Alan Gauld alan.gauld@blueyonder.co.uk
Wed Jun 25 15:28:03 2003


> >> lineCount = 0
> >> for line in f.xreadlines():
> >>     print lineCount, line
> >>     lineCount += 1
>
> What you start with seems like the more aesthetic,
> Pythonic type form. And its rather nicer to keep the
> plain English interpretation of just the two lines.
> What I'm saying is, well most languages have this
> FOR command, and they all generally use it to count
> sequentially, with some options sometimes.

While its true that most languages have a numerically oriented FOR
loop, many also have a FOREACH loop construct. Python just
happens to call its FOREACH construct FOR...

> So it would be neater if Python kept to that tradition.
> and had an implied counter for any structure like that,

Why? It's not that often you need to know the count if you are
processing everything in a list - which is what the FOR loop is for!

> I was thinking you could probably access the counter out of
> >> for line in f.xreadlines():
> >>     print line
>
> Since, to do what you're asking of it, it has to be keeping
> track with exactly this kind of integer counter.

Why? What makes you think that. It could just keep processing things
till it runs out of items to process. It doresn't need to keep a
counter.

Consider the common case of processing a file with a while loop
until you reach the end of file... You don't need to track the
line number.

> When you have to add extra variables, it just adds more text on your
> screen, and less space to review the main stuff you've actually
> written.

For the relatively few cases where you need an index counter then
the amount of extra text is small, and you have the choice of using
a while loop, or for loop. Mostly when you use a for loop you just
want to process each item.

Alan G.