When we want to do an in place increment/decrement/…
We could use something like this,
a = 1
a += 1
but, if I have a string and I want to make it upper case, then, I need to do something like,
attribute = 'abc'
attribute = attribute.upper()
I need to use the
attribute term on the right side also.
what could be the reason for there being no,
so that repeating the same term on the right side could be avoided.
this applies for other methods also, like
or, let us say, I want to do something like,
attribute_2 = ['abc', 'def']
attribute_2 = list(map(lambda x: x.upper(), attribute_2))
then, again, I need to specify,
attribute_2 on the right side.
what could be a way to avoid using the same term on the right side?
Integers and strings are immutable. Methods like
some_string.upper(inplace=True) can never exist. Also, the “in-place increment”
a+=1 isn’t really in-place, it’s just short for
a=a+1. To check this:
a = 42
b = a
assert a is b # check that a and b are the same int object
a += 1
print(a, b) # prints 43 42 because `b` hasn't changed
If you could mutate the integer 42 in-place to become 43, then that last print would show “43 43”.
As for lists, in principle there could exist mutating methods like
my_list.replace_each(lambda x: x.upper()), but AFAIK you need to “specify the name of the variable on both sides of the assignment operator” as you said.
BTW, instead of
list(map(...)), using list comprehensions is usually clearer:
mylist = [x.upper() for x in mylist]
but if I implement my custom
upper method, something like this,
def upper(self, in_place=False):
CustomString.__repr__ = lambda x: x.upper(in_place=True)
a = CustomString('abc')
but there is some implementation issue, as I changed the
__repr__ itself, probably there would be a better way to implement it, as,
b = CustomString('aaa')
is there a way to create a custom mutable string?