1

Why does this evaluate to type string:

>>> strng = 'spam'
>>> type(strng.replace('a', 'A')) 
>>> <type 'str'>

but this evaluates to type NoneType?

>>> list_a = ['spam']
>>> type(list_a.append('eggs')) 
>>> <type 'NoneType'>

4 Answers 4

6

Because the append method on the list returns a None (or, said another way... doesn't return anything), as it mutates the list.

Most, if not all, mutating methods in python's standard library act this way.

replace on the string, does not mutate, as python strings are immutable. A new string is returned with the replacements made.

Sign up to request clarification or add additional context in comments.

Comments

4

If you look at your commands a bit more, you will see this:

>>> strng.replace('a', 'A')
'spAm'
>>>

Notice how this method returns something. When you call type(), you are basically calling this:

>>> type('spAm')
<type 'str'>
>>>

Now your next line of code:

>>> list_a.append('eggs')
>>>

Notice that nothing was returned. When you call type() on this, you are basically calling type() with a None parameter:

>>> type(None)
<type 'NoneType'>
>>> 

Comments

2

Strings are immutable, so the only reasonable thing for replace to do would be to return the changed value. Lists are mutable, though, so append doesn't have to return anything, and if there is no explicit return, it returns None. You could say that append should return something, but that may lead people to believe that append does not mutate the list.

Comments

2

Because str.replace() returns a new string with the modified value, while list.append() modifies the list in place, not returning a value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.