are strings in python mutable, if not explain this? [duplicate] - python

This question already has answers here:
Aren't Python strings immutable? Then why does a + " " + b work?
(22 answers)
Closed 3 years ago.
I have declared a string "y as hello than tried to change character "h" by "m" using replace method in python and i checked for the type(y): its showing string
but when I googled, its showing strings are immutable... please explain
>>> y="hello"
>>> y=y.replace("h","m")
>>> y
'mello'
>>> type(y)
<class 'str'>

You didn't mutate the String, you changed what String y pointed to.
y originally pointed to "hello", then you ran the line y=y.replace("h","m") and caused y to instead point to the String "mello". The original String "hello" was never mutated, since Strings are indeed immutable.

Yes, strings are immutable. When you run the line
y=y.replace("h","m")
you are creating a new string, not changing the first one. The first string can't actually be changed.

String in Python are immutable (cannot change to allow for optimization of using one dictionary for all strings).
For example:
>>> y="hello"
>>> y.replace("h","m")
'mello'
>>> y
'hello'
When we want to change a string, we can either use bytearray or (often better) - just create a new string. Consider for example the method 'replace'. It did not change the string in the example - but we could assign it's return value.
>>> y1 = y.replace("h","m")
>>> y1
'mello'
Or even use the same variable y, in which case it will create a new string and overwrite the previous value of y.
>>> y = y.replace('h','m')
>>> y
'mello'
Which is just like putting a new value alltogether:
>>> y = 'a new value'
>>> y
a new value

Related

Not too sure about replace() function on Python - why isn't dog being replaced with cat? [duplicate]

This question already has answers here:
python: why does replace not work?
(2 answers)
Closed 1 year ago.
a = 'dog'
a.replace('dog', 'cat')
print (a)
Really basic question, the function seems to be fairly straightforward but it just isn't replacing in this instance for some reason - is it because replace doesn't inherently change "a"?
Yes, you are correct. It won’t modify a.
Replace function will return a replaced string.
So, if you like to replace the text in a. Use the below code.
a = 'dog'
a = a.replace('dog', 'cat')
print (a)
Strings are immutable data types in Python which means that its value cannot be updated. Variables can point at whatever they want.
str.replace() creates a copy of string with replacements applied. See documentation.
Need to assign a new variable for the replacement.
a = 'dog'
b = a.replace('dog', 'cat')
print(b)
Output:
cat

Python 3 integer addresses [duplicate]

This question already has answers here:
The `is` operator behaves unexpectedly with non-cached integers
(2 answers)
Closed 1 year ago.
x=300
y=300
print(id(x),id(y))
a=[300,300]
print(id(a[0]),id(a[1]))
On executing above code I get different addresses for x and y but the same address for a[0] and a[1]. Can anyone tell me why that is happening?
Take a look at below example:
>>> a=256
>>> b=256
>>> print(id(a),id(b))
(31765012, 31765012)
>>>
>>> c=257
>>> d=257
>>> print(id(c),id(d))
(44492764, 44471284)
>>>
This will help you understand the unexpected behavior for integers. Whenever you create a int in range -5 to 256 you actually just get back a reference to the existing object. This is called Integer Caching in python.
In CPython, the C-API function that handles creating a new int object is PyLong_FromLong(long v). see the documentation on this link
EDIT: Now coming to the list. For the same list elements (larger integers) you are getting same id's because list is created at once or you can say in one go.
You can achieve similar behavior with integers as well, see below example with parallel assignment.
>>>
>>> a,b = 300,300
>>>
>>> print(id(a),id(b))
(36132288, 36132288)
>>>
Hope this will clear your doubts.

Why doesn't Python return an error for string assignment using replace in a for loop? [duplicate]

This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 6 years ago.
In the following example, I would have expected an error saying that string assignment is not possible because strings are immutable. Instead, the loop returns the original string.
a = "AECD"
for i in a:
if i == "E":
a.replace(i, "B")
print(a)
Is replace not essentially trying to do the same thing as a[1] = "B"? Does this have to do with creating a new object with assignment versus modifying an existing one with replace?
a.replace(i, "B")
does not change the original string a. Instead, it returns the string which results from replacing i in a.
In your loop, you are merely evaluating an expression and dropping it on the floor.
You could do it this way:
a = "AECD"
for i in a:
if i == "E":
a = a.replace(i, "B")
print(a)
In this version, you take the string with the replacement, and you assign that value to the variable a, which gives you the effect you were expecting.
Try this:
a = "AECD"
for i in a:
if i == "E":
b = a.replace(i, "B")
print (b)
print(a)
Since you're not doing a string assignment, this is not an error. A new string is being created and is returned by the str.replace() method. You are throwing it away by not assigning it to anything, however.

Query on Name & object in Python [duplicate]

This question already has answers here:
About the changing id of an immutable string
(5 answers)
Closed 8 years ago.
In Interactive mode of python, When i say,
>>> mystr = 'abc'
we have object created in the current frame of type string with content 'abc'
Now, If i change the binding of mystr as shown below,
>>> mystr = 'def'
then, the name mystr will bind to a new object with the content 'def'.
We know that string are immutable objects, so object containing 'abc' gets unaffected.
In my machine it works like this:
>>> mystr = 'abc'
>>> id(mystr)
30868568
>>> mystr = 'def'
>>> id(mystr)
36585632
>>> mystr = 'abc'
>>> id(mystr)
30868568
My question:
How does Python environment deal with object containing 'abc' after new binding, Will it purged?
Strings are mutable, references are not.
When you assign str to "def", the other string "abc" does not affects. Just str's content will change, and it will reference to new "def" object.
When you manipulate strings in python, java etc.. languages such taking substring, it will make a new string object.
-For extra information (performance tips) if you work with strings for manipulating them use StringBuilder.

Python: what difference between 'is' and '=='? [duplicate]

This question already has answers here:
Is there a difference between "==" and "is"?
(13 answers)
Closed 9 years ago.
I'm trying next code:
x = 'asd'
y = 'asd'
z = input() #write here string 'asd'. For Python 2.x use raw_input()
x == y # True.
x is y # True.
x == z # True.
x is z # False.
Why we have false in last expression?
is checks for identity. a is b is True iff a and b are the same object (they are both stored in the same memory address).
== checks for equality, which is usually defined by the magic method __eq__ - i.e., a == b is True if a.__eq__(b) is True.
In your case specifically, Python optimizes the two hardcoded strings into the same object (since strings are immutable, there's no danger in that). Since input() will create a string at runtime, it can't do that optimization, so a new string object is created.
is checks not if the object are equal, but if the objects are actually the same object. Since input() always creates a new string, it never is another string.
Python creates one object for all occurrences of the same string literal, that's why x and y point to the same object.

Categories