0

Hopefully not a silly question. If I write

str1 = 'exterminate!'           

str1.upper()

print(str1)

str1 = str1.upper()

print(str1)

my_list = [1, 2, 3]

my_list.append(4)

print(my_list)

my_list = my_list.append(5)

print(my_list)

The output is:

exterminate!
EXTERMINATE!
[1, 2, 3, 4]
None

In other words,

str1.upper()

and

my_list.append(4)

do very different things. By that, I mean .append actually changes the list object, but .upper() does not.

However, in order to change the string object to all uppercase, we have to use

str1 = str1.upper()

but doing

my_list = my_list.append(5)

we now have my_list as a noneType.

Can someone explain this behavior. I have a feeling it has to do with the fact that they are different object types.

1

4 Answers 4

3

Strings are immutable in Python.

Therefore, they don't offer in-place modification. The form foo = foo.upper() is therefore the usual way to do it for Python.

Note that a variable is not in itself immutable, meaning that when you do foo = foo.upper(), Python will return a new uppercase string based on the string pointed to by foo, then update the variable foo to point to that new string. (The old string may then be removed from memory, if its reference count goes to zero.)

Some other data structures in Python are also immutable, for example tuples like t = (1,2,3). To modify those, you'd need to construct new tuples.

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

Comments

2

Strings in Python are immutable. They can't be changed. This is why all the string methods return a new string instead of modifying the string in place. Lists on the other hand are mutable, and generally list methods mutate the list in place, and return None.

This is a general rule (with some exceptions): Mutating methods return None, while non-mutating methods return a new value.

Comments

0

upper() method returns a copy of a string. See docs for reference.

Comments

0

the .upper() method does not change anything in your String but it return a new string that is with the upper words and you need to save that output in a variable. but in .append() method add your input in the list and you don't need to use my_list = my_list.append(5)

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.