Too Self Centered

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Jan 13 09:48:38 EST 2003


> From: Andres Rosado [mailto:arosado at softhome.net]
> Sent: Friday, January 10, 2003 7:09 PM
> 
> On 09:21 PM 1/7/2003 -0500, the keyboard of 
> python-list-request at python.org 
> emitted:
> >     def __init__(self):
> >           f = open('test1','r')
> >           while f.readline()!=''
> >                 i += 1
> >           self.total = i
> >           f.close()
> 
> Or
> self.total = len[x for x in f.readlines() if x != '']
> 
> If you use list compression.
> --
> Andres Rosado

Or, it can be further reduced to:

  self.total = len([x for x in f if x])

since the expression (x != '') is equivalent to (x),
because an empty string is "False".  Another, if you're
using a python version >= 2.2, you can ommit the .readlines()
call, because files have __iter__ attributes, which are
automagically used by the for statement.


Also, you forgot len's parenthesis. :-)

-gustavo





More information about the Python-list mailing list