Search code examples
pythonpython-2.7typeerror

why cannot invoke remove directly after split a string in python?


I wanted to remove a substring from a string, for example "a" in "a,b,c" and then return "b,c" to me, it does not matter what's the order of a in string(like "a,b,c", "b,a,c", and so one).

DELIMITER = ","
def remove(member, members_string):
    """removes target from string"""
    members = members_string.split(DELIMITER)
    members.remove(member)
    return DELIMITER.join(members)

print remove("a","b,a,c")

output: b,c

The above function is working as it is expected.

My question is that accidently I modified my code, and it looks as:

def remove_2(member, members_string):
    """removes target from string"""
    members = members_string.split(DELIMITER).remove(member)
    return DELIMITER.join(members)

You can see that I modified

    members = members_string.split(DELIMITER)
    members.remove(member)

to

    members = members_string.split(DELIMITER).remove(member)

after that the method is broken, it throws

    Traceback (most recent call last):
      File "test.py", line 15, in <module>
        remove_2("a","b,a,c")
      File "test.py", line 11, in remove_2
        return DELIMITER.join(members)
    TypeError

Based on my understanding, members_string.split(DELIMITER) is a list, and invokes remove() is allowed and it should return the new list and stores into members, but when I print members_string.split(DELIMITER) it returns None, it explains why throws TypeError, my question is , why it returns None other than a list with elements "b" and "c"?


Solution

  • remove() does not return anything. It modifies the list it's called on (lists are mutable, so it would be a major waste of cpu time and memory to create a new list) so returning the same list would be somewhat pointless.