slicing lists

Yves Dorfsman yves at zioup.com
Fri May 9 01:15:21 EDT 2008


MRAB wrote:

> You should've read the thread entitled "Why don't generators execute
> until first yield?"! :-) Michael Torrie gave the URL
> http://www.dabeaz.com/generators/Generators.pdf. Your example can be
> rewritten as follows:
> 
> p = file('/etc/passwd') # No need for readlines() because file's
> iterator yields the lines.
> r = ( e.strip().split(':') for e in p ) # A generator expression
> instead of a list comprehension.
> s = [  e[0:1] + e[2:]   for e in r ]

Thanks, this is very elegant indeed, but because there are two list 
comprehension expressions (the one defining r and the one defining s), it 
means that the we're looping twice over the same list instead of once with 
the e[0,2:] hypotetical notation ; or am I missing something ?

Yves.
http://www.SollerS.ca



More information about the Python-list mailing list