Why are Python strings immutable?

programmingshark.com- programming assignment help company provides information about python string immutable.

There are several advantages.
One is performance: knowing that a string is immutable makes it easy to lay it out at construction time — fixed and unchanging storage requirements. This is also one of the reasons for the distinction between tuples and lists. This also allows the implementation to safely reuse string objects. For example, the CPython implemenation uses pre-allocated objects for single-character strings, and usually returns the original string for string operations that doesn’t change the content.
Note- Student searching for Python programming assignment help.
The other is that strings in Python are considered as
elemental
as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string “eight” to anything else.
When you receive a string, you'll be sure that it stays the same. Suppose that you'd construct a Fooas below with a string argument, and would then modify the string; then the Foo's name would suddenly change:
  1. class Foo(object):
  2. def __init__(self, name):
  3. self.name = name
  4.  
  5. name = "Hello"
  6. foo = Foo(name)
  7. name[0] = "J"
With mutable strings, you'd have to make copies all the time to prevent bad things from happening.
It also allows the convenience that a single character is no different from a string of length one, so all string operators apply to characters as well.
And lastly, if strings weren't immutable, you couldn't reliably use them as keys in a dict, since their hash value might suddenly change.
As for programming with immutable strings, just get used to treating them the same way you treat numbers: as values, not as objects. Changing the first letter of namewould be
  1. name = "J" + name[1:]

Comments

Popular posts from this blog

html sitemap 15

html sitemap 16

What are some good programming languages to learn now?