Search code examples
python-3.xfor-looplist-comprehension

List comprehention works but normal for loop doesn't - Python


I defined a function to change an element of a list to be number 0, if this element is not a number. It works using list comprehension but it doesn't work when I use a normal for loop. I'm trying to understand what's is the error in the for loop.

See the code below:

def zerozero(mylist):
    
    mylist = [0 if type(x) == str else x for x in mylist]
    
    return mylist


def zerozero2(mylist):
    
    for x in mylist:
        if type(x) == str:
            x = 0
        else:
            x = x
    return mylist

Solution

  • Your second function is not quite equivalent. You would need something like this:

    def zerozero2(mylist):
        new_list = []
        
        for x in mylist:
            if type(x) == str:
                new_list.append(0)
            else:
                new_list.append(x)
        return new_list
    

    In this manner you can mimic the functionality of the list comprehension, creating a new list and appending items to it as you iterate through.

    If you want to modify your list 'in place', you can use this sort of construction:

    for idx, x in enumearte(mylist):
        if type(x) == str:
                mylist[idx] = 0
            else:
                mylist[idx] = x
    

    However, practically speaking this is unlikely to have much impact on your code efficiency. You can't do this with a list comprehension, and in either case you can just re-assign the new list back to your original variable when you return from the function:

    mylist = zerozeroX(mylist)