Equivalent string.find method for a list of strings

Steven Bethard steven.bethard at gmail.com
Fri Apr 8 21:46:16 EDT 2005


jeremit0 wrote:
> Steve Holden wrote:
> 
>> If you want line numbers,. of course, then you can use
>>
>>   for linenum, line in enumerate(myfile.readlines()):
>>       ...
>>
>> Remember that true to Python's philosophy numbering will start at zero.
>>
> Is this any better than:
> 
>     lines = myfile.readlines()
>     for linenum in xrange(len(lines)):
>         # Do stuff with lines[linenum] ...

Well, if you use lines[linenum] often in that code, it'll be more 
efficient to use enumerate (or bind lines[linenum] to a name, which is 
basically what enumerate is doing for you).  Given the file test.py:

--------------------------------------------------
def elines(lines):
     for linenum, line in enumerate(lines):
         x = linenum
         y = line
         z = line

def xlines(lines):
     for linenum in xrange(len(lines)):
         x = linenum
         y = lines[linenum]
         z = lines[linenum]

--------------------------------------------------

Here's what I get with timeit:

[D:\Steve]$ python -m timeit -s"lines = range(10000); import test" 
"test.elines(lines)"
100 loops, best of 3: 2.85 msec per loop

[D:\Steve]$ python -m timeit -s"lines = range(10000); import test" 
"test.xlines(lines)"
100 loops, best of 3: 3.18 msec per loop

The other thing worth noting is that enumerate will work with any 
iterable, while your xrange technique won't.  Try:
     for linenum, line in enumerate(myfile):
         ...
and
     for linenum in xrange(len(myfile)):
         line = myfile[linenum]
         ...
and see what kind of cool errors you get with the xrange solution. :)

STeVe



More information about the Python-list mailing list