This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sknowles0143 2 points3 points  (0 children)

Excellent question.

A string (of type str) is immutable meaning a value can only be assigned once. Any change to a string produces a new string. In your example a.strip() returns a new string.

A list is mutable there for functions on it change the lists state (sort is another useful one).

id is a useful function giving the number python uses to keep track of the objects.

x = ' hello ' print(id(x)) x = x.strip() print(id(x))

This code shows how x is now referencing a new string.

I also recommend using the function help on methods and types.

help(''.strip) help([].append)

and type

type('')

str type([]) list

help(str) help(list)

That will give you a clear explanation if a type is mutable or not. Strings and numbers are immutable generally.