[Tutor] Readlines

Rodrigues op73418@mail.telepac.pt
Wed Jun 25 17:59:01 2003


> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Adam Vardy
>
> Tuesday, June 24, 2003, 6:01:33 PM, you wrote:
>
> So it would be neater if Python kept to that tradition. And
> had an implied
> counter for any structure like that, without having to
> declare a variable
> counter, like it was a low level kind of language.
>

Not really. Python >= 2.2 by breaking tradition, subsumes all for-loop
considerations into the concept of iterable object. An iterable object
is an object that like list, tuple, dict, etc. can be iterated over.

> 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.
>
> 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.
>

Python 2.3 comes with the enumerate builtin to neatly solve this. In
2.2 you can code it using generators. I suggest that you learn these
new features, and to wet the appetite I'll just give Python code for
the enumerate built-in

>>> from __future__ import generators
>>> def enumerate(iterable):
... 	counter = 0
... 	for elem in iterable:
... 		yield (counter, elem)
... 		counter += 1
...
>>> for elem in enumerate(range(5)):
... 	print elem
...
(0, 0)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
>>> f = file(r"C:\test.txt")
>>> for pair in enumerate(f):
... 	print pair
...
(0, 'this\n')
(1, 'is\n')
(2, 'a\n')
(3, 'test\n')
(4, 'for\n')
(5, 'demonstration\n')
(6, 'purposes')
>>> f.close()
>>>

With my best regards,
G. Rodrigues