1

There's a phenomenon I've noticed in Python that I'd like to understand but I don't know what words to use to describe it or find documentation.

Compare the following sequences:

1)

a = ['my', 'nice', 'new', 'list']
a.reverse()
print(a)

>>> ['list', 'new', 'nice', 'my']

2)

b = 'my nice new string'
b.swapcase()
print(b)

>>> 'my nice new string'

Why is it that, for the second sequence, in order for print to give 'MY NICE NEW STRING', I would have to write

b = b.swapcase()
print(b)

? Or conversely, why DON'T I have to write a = a.reverse() before print(a) in the first sequence? What is the principled reason for why some of these methods need to be explicitly assigned to variables while others are implicitly stored in the variable that they're used upon?

0

2 Answers 2

2

Some functions modify the list, some return a modified version. For example .reversed() instead of .reverse() would return a reverse-sorted list instead of modifying the list itself. For mutable objects such as lists, dicts, etc. you have the option to modify the object itself.

You can't have a version of .swapcase() that modifies the original string though since strings are immutable:

https://docs.python.org/2/reference/datamodel.html

Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

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

Comments

0

The list is a reference variable to a mutable data structure. Calling it's reverse method reverses the list "in place".

The swapcase method returns a new string because strings are immutable in Python

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.