-13
  1. The first I'll write a simple program:
s = "Taxi" 
output will be: 
Taxi 
  1. Then I'll replace the First index (T) To (S): but before I do anything How string is immutable and I can replace it ,, Is it immutable because the id of the first index will be take the old id ..

FOR illustration :

id(T) = 1100
and id(S) = 1100   
4
  • Can't see what T is. But yes, str is immutable, as in you can't do s[0] = 'M' Commented Aug 24, 2020 at 8:31
  • Checkout Mutability and Immutability in Python — Let’s Break It Down Commented Aug 24, 2020 at 8:34
  • You should read the following as well: nedbatchelder.com/text/names.html Commented Aug 24, 2020 at 8:54
  • 2
    "Then I'll replace the First index (T) To (S): but before I do anything How string is immutable and I can replace it ,, Is it immutable because the id of the first index will be take the old id .." What does this even mean? Please be specific. Commented Aug 24, 2020 at 8:55

1 Answer 1

-1

The fact that the ids were the same implies that they are pointing on the same object.
String in Python is immutable, you can't assign to it's indexes values.



Immutability means that we can change the original object:

# List is mutable
l = [1, 2, 3]
# That's OK
l[0] = 5
# String is NOT mutable
s = '123'
# That's NOT OK - and WON'T work!
s[0] = '5'




The following assignment means that we create another pointer, to the same string:

S = "Taxi"
T = "Zaxi"
# The following line of code will cause 'S' point on 'T' string
# The string referenced by 'S' before has not changed! (and not available)
S = T
# Assertion will pass, as we changed S to point on T, now they point on same string
assert id(S) == id(T)


The fact that strings are immutable makes it memory-inefficient to generate new strings based on existing strings.
In C#, where strings are immutable too, there is a class called StringBuilder which mitigates this in-efficiency.
On other alternatives to StringBuilder in Python read more in this great thread.

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

4 Comments

This doesn't demonstrate immutabliity at all. Try this with mutable types, S = [1, 2, 3] and T = ['a','b','c'] and S = T will give you id(S) == id(T), indeed, for python for any objects a and b, a = b will imply a is b, that's merely the semantics of assignment
@juanpa.arrivillaga That's exactly what I wrote. Added more clarification regarding the meaning of mutability versus non-mutability. Thank you for your comment.
I think I follow you now, yes.
thank you , acutely i am beginner in the language and i try to know everything

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.