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

Time:10-19

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

CodePudding user response:

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)

CodePudding user response:

So what happens is your function is returning the same list as your input.

What you should do is create an empty list first. For example my_list_0 = [].

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

The list comprehension essentially returns the new values into your original list, so this is why it is different.

  • Related