Question of split() and append()


#1

During the censor function problem, I found out that when I use split() or replace() function on a list, if I type:
List.split()
List.replace()
Then in the next row, when I call List again then List will remain unchanged, unless I save it in a List target:
List = List.split()
List = List.replace()
Then the function may work properly. However, while I use append() function:
List.append()
in a single line, in the next row the original List DOES changed. I don't understand the difference between these functions, why one should be saved to a target list and another don't need to.

Can anyone answer me? Thanks!


#2

this has to do with the way the function are designed.

split() and replace() return a new list, for example:

def example():
    return [1,2,3]

x = example()

given the above function returns something, we need to store the returned result in a variable, where as append() modifies the list and doesn't return anything

But given function always need to return something, append() returns None (the default), which is why its very important not to do List=List.append(), because then you store None in the variable, overwriting the list

I can't tell you why this design choices where made


#3

Thanks, I got it.So the problem is that whether the function returns a value or not.
That's what I want to know.


#4

yes, returns a value (split and replace do this) or that the list is modified directly (append), which i guess is done to save memory


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.