• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Why Strings in Python are Immutable | String Immutability Explained !

  • September 18, 2022
  • CODE OF GEEKS
  • 0

Python Strings: In this Unit…

  • Strings in Python, Slicing and Basic Operations
  • String Immutability Explained
  • strip() method in Strings
  • find() method in Strings
  • count() method in Strings
  • replace() method in Strings
  • split() method in Strings
  • Switching Cases in Strings
  • startswith() method in Strings
  • endswith() method in Strings

In this article, we will be exploring on Python String’s Immutable Nature and how they are actually stored in the memory.

Before we move further, we will suggest you to re-visit your knowledge of Python Strings by checking this awesome tutorial on Python Strings .


What is the concept of Immutability ?

An immutable object is an object whose content (data stored in that object) can not be changed. If we talk about Python specifically, we have Numbers, Strings and tuples as immutable.

Immutable objects are better than Mutable objects in terms of performance and security.

Strings are Immutable. Why

Reason is simple, we can not modify the content of String object. Okay, but how ?

Let’s see an example to prove our point –

s = "code with me" 
s[1] = 'k' # modifying the second character of string to 'k'
print(s) 

In the above code, we have defined a string object, and we are trying to modify the second character of that string.

After running the code, we got an error -> TypeError: ‘str’ object does not support item assignment.

This error is the result of String’s Immutable Nature, which will not allow us to modify the content of any string object.

Now, look at this code –

s = "code with me"
print(s.replace('o', 'k', 1)) # replacing the first occurrence of 'o' with 'k'

str.replace() -> Method Definition

Python String’s replace() method is used to replace one character or a subtring with another character or substring.

string.replace(old, new, count)

old : The string to search for
new : The string to replace the old value with
count : A number specifying how many occurrences of the old value you want to replace.

O/P : ckde with me

So, why this worked ? Isn’t that violating Strings Immutability Nature ?

No, its not. To justify this, let’s try to print the memory id for both statements,

s = "code with me"
print("Id of Replaced String : ", id(s.replace('o', 'k', 1))) 
print("Id of Original String : ", id(s))

O/P :

Id of Replaced String : 2221657042160
Id of Original String : 2221657028016


Now, memory id for both is different. Hence, these are two different objects.

replace() method creates the copy of original string and modifies it. Hence, you are not seeing that Type Error anymore.

Let’s take one more ambiguous example,

In this example, we are creating two strings, ‘s1’ and ‘s2’ as :

s1 = "sun"
s2 = "fun" 

Now, let’s assign content of s1 to s2.

s2 = s1 
print(s2) # prints 'sun'

So, are they equal now ? Yes, they are. Again, isn’t that violates the String’s Immutability Nature ?

By looking at the code, it seems that content of s2 is replaced by the content of s1 and hence s2 became mutable. This is wrong assumption.

When we write, s2 = s1, the name ‘s2’ will be adjusted to refer to the object that is referred by ‘s1’. But, the original value of s2′ (which is “fun”) is not altered.

Since, “fun” is not referenced, the garbage collector deletes that object from memory. You can read this article to get more clear picture on Python Garbage collection.

String Immutability
s1 = "sun"
s2 = "fun"
print("Memory Id of s1", id(s1))
print("Memory Id of s2", id(s2))
s2 = s1
print("Memory Id of s1", id(s1))
print("Memory Id of s2", id(s2))

O/P :

Memory Id of s1 1496817399216
Memory Id of s2 1496817399344
Memory Id of s1 1496817399216
Memory Id of s2 1496817399216

We can see that initially, id for both s1, s2 was different, but after modification, their id became equal, and hence, s2 started referencing the new object.

In our opinion, this must be the best thing you know now. Please share and help us to reach out the corners of world.

Thanks and cheers.



Tags: how are strings stored in memoryPython stringswhy are python strings immutablewhy are strings immutable
  • Previous string.strip() method in Python Strings
  • Next How to post HTML form data in NodeJS or Express Server with Source Code

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.