only mutable objects can be changed in-place; strings, tuples, and other objects will always have to create new objects if you change them. What does in-place mean here,and why tuples, strings are special cases here
0
votes
in place is hic et nunc - you can manipulate them as you want. del your_list[i] will delete ith item in your list and this will make actual change in your list object. but you cant do the same thing to strings. if you want to change a = "string" to somthing else, you have to create another b variable keeping manipulated string object in it. as you expect a is unchanged. you can just destroy or assign the memory place this variable holds, to the b, like a=b.
- marmeladze
@Martijn: The phrase "in-place" is not explained on the dupe page.
- unutbu
@unutbu: does it really matter here? At issue is understanding what the difference between the two types of objects is.
- Martijn Pieters♦
@Martijn: The distinction may not matter to you because you know what "in-place" and "mutable" mean, but it may not be so clear to someone trying to learn the meaning of the terms. A person looking for the definition of "in-place" won't find it on the dupe page since the dupe page never mentions the term. Since the terms "in-place" and "mutable" are not fungible, I think it would be nice to address the OP's question directly.
- unutbu
@unutbu: I see that the top answer already uses the phrase "in place". In my mind it just an expression. I'm still not sure that the idiom needs explaining here when the concepts are already well enough covered. Re-evaluating this post and the dupe, I see no point in explaining that separately, really.
- Martijn Pieters♦
1 Answers
3
votes
In Python a variable holds a reference to an object.
To "change" a variable, you may either change the referenced object. Or reference an other object.
"Immutable" object force you to use the first solution as the object by itself cannot be modified. "Mutable" objects give you the choice between the two options.
As string are immutable, you cannot "change" a string object. All you can do, is create a new string and update the reference to hold that newly created string:
>>> v1 = v2 = "hello"
>>> v1 += "world"
# v1 and v2 no longer references the same object:
>>> v1 is v2
False
>>> v1
'helloworld'
>>> v2
'hello'
But as list are mutable you have the choice to change them "in place":
>>> v1 = v2 = ['h', 'e', 'l', 'l', 'o']
>>> v1 += ['w', 'o', 'r', 'l', 'd']
# v1 and v2 still references the same object:
>>> v1 is v2
True
>>> v1
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> v2
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
Or to create a new list and update the reference:
>>> v1 = v2 = ['h', 'e', 'l', 'l', 'o']
>>> v1 = v1 + ['w', 'o', 'r', 'l', 'd']
# v1 and v2 no longer references the same object:
>>> v1 is v2
False
>>> v1
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
>>> v2
['h', 'e', 'l', 'l', 'o']