Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #71546

Re: New to Python. For in loops curiosity

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: New to Python. For in loops curiosity
Date 2014-05-14 07:38 -0400
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-B8E824.07382614052014@news.panix.com> (permalink)
References <2f08e970-1334-4e7f-ba84-14869708a73b@googlegroups.com>

Show all headers | View raw


In article <2f08e970-1334-4e7f-ba84-14869708a73b@googlegroups.com>,
 Leonardo Petry <leonardo.petry.br@gmail.com> wrote:

> Basically my question is: Why is python not treating the contents of 
> [a file] as one long string and looping each character?

Because whoever designed the original file object decided that the right 
way to iterate over a file is line by line.  In Python (although, at 
this level of explanation, I could be describing pretty much any 
language which has iterators), there is an iterator protocol which 
implements two ideas:

1) There's a method to call to get the next item.

2) There's a way for that method to signal that you've reached the end.

Exactly what "the next item" means is up to whoever implements the 
iterator.  In this case, it was decided that the most convenient thing 
would be for "item" to mean "line".  If you really want to iterate over 
a file character-by-character, it's easy enough to write an adapter.  
Something like this (untested):

def getchar(f):
   for line in f:
      for c in line:
         yield c

Of course, if the native file iterator was character-by-character, then 
if you wanted it line-by-line, you would have to write the inverse, a 
function which accumulates characters until it sees a newline, and then 
returns that.  Neither one is fundamentally better, or more correct than 
the other.  One may just be more convenient for a particular use case.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

New to Python. For in loops curiosity Leonardo Petry <leonardo.petry.br@gmail.com> - 2014-05-13 20:38 -0700
  Re: New to Python. For in loops curiosity John Gordon <gordon@panix.com> - 2014-05-14 03:46 +0000
  Re: New to Python. For in loops curiosity Rustom Mody <rustompmody@gmail.com> - 2014-05-13 20:48 -0700
  Re: New to Python. For in loops curiosity Ian Kelly <ian.g.kelly@gmail.com> - 2014-05-13 21:49 -0600
  Re: New to Python. For in loops curiosity Ben Finney <ben@benfinney.id.au> - 2014-05-14 14:03 +1000
  Re: New to Python. For in loops curiosity Roy Smith <roy@panix.com> - 2014-05-14 07:38 -0400
  Re: New to Python. For in loops curiosity Ned Batchelder <ned@nedbatchelder.com> - 2014-05-14 09:41 -0400

csiph-web