[Tutor] iterating in the same line

Bob Gailer bgailer at alum.rpi.edu
Sun Aug 14 00:49:26 CEST 2005

At 12:20 PM 8/13/2005, Jonas Melian wrote:
>I would check 3 words at the starting of a line
>if ln.startswith(s):   (this is bad)
>what is the best way for making it?

Iterations over a list of this nature are most succinctly done using list 

if [l for l in s if ln.startswith(l)]:

Caveat: This will test every word in s. If s is a large list it would be 
more efficient to break as soon as a match is found:

match = False
for l in s:
     if ln.startswith(l):
         match = True

The 3rd alternative is to use regular expression matching. That is beyond 
the scope of this thread.

Bob Gailer
mailto:bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 

More information about the Tutor mailing list