[Tutor] for/else question
Michael Janssen
Janssen at rz.uni-frankfurt.de
Fri Sep 12 15:54:23 EDT 2003
On Thu, 11 Sep 2003, Gabriel Cooper wrote:
> So... yeah... Do /you/ use "else" with for loops? If so, when?
some time ago it has really helped me out of an ugly function:
def delpattern(inlist, patternl):
"""clean inlist from entries with certain sub-strings"""
backl=[]
for elem in inlist:
for pattern in patternl:
if elem.find(pattern) >-1:
break
else:
backl.append(elem)
return backl
#without for-if-else it would be (under the assumption you don't want
#to investigate further to get some clever list-comprehension or reg-exp
#solution):
def delpattern(inlist, patternl):
"""clean inlist from entries with certain sub-strings"""
backl=[]
for elem in inlist:
found = 0
for pattern in patternl:
if elem.find(pattern) >-1:
found = 1
break # just to save time
if not found:
backl.append(elem)
return backl
for-if-else seems much more readable (understandable) than
found-not-found to me. You have compared looking for something to doing
something. Here we're looking for something and only doing if not found.
Michael
More information about the Tutor
mailing list