[Tutor] for/else question

Gabriel Cooper gabriel.cooper at mediapulse.com
Fri Sep 12 18:20:02 EDT 2003



Michael Janssen wrote:

>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
>
>  
>

Hm... Still not convinced. Why not do it this way:

def delpattern(inlist, patternl):
    list_copy = inlist[:]
    for p in patternl:
        for elem in inlist:
            if elem.find(p) > -1:
                list_copy.remove(elem)
    return list_copy






More information about the Tutor mailing list