Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Modify Strings
Next article icon

Why are Python Strings Immutable?

Last Updated : 21 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Strings in Python are “immutable” which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc. 

The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc.

The article will explore the differences between mutable and immutable objects, highlighting the advantages of using immutable objects. It will also compare immutability with mutability, discussing various methods to handle immutability and achieve desired outcomes.

Input:  name_1 = "Aarun" 
name_1[0] = 'T'
Output: TypeError: 'str' object does not support item assignment
Explanation: We cannot update the string after declaring it means once an immutable the objects instantiated, its value cannot be changed

Python Strings Immutability

Immutability is the property of an object according to which we can not change the object after we declared or after the creation of it and this Immutability in the case of the string is known as string immutability in Python.

Work with Mutable and Immutable Objects

The immutable term generally refers to their property of being immune to change or modification after their creation, the same case with the string data type in Python which is immutable.

Some other datatypes in Python are immutable such as strings, numbers (integers, floats, complex numbers), tuples, and frozensets.

Mutable objects are that we can modify according to our requirements and use according to our use. A few examples of them are List, Dictionary, and Set.

Example:

In the below code, we declare a string and assign it to modify the “my_string” variable, after that we try the string.

Python3




my_string = "Hello, world!"
 
# Attempt to modify the string
my_string[0] = 'h'  # Raises TypeError: 'str' object does not support item assignment-----
 
 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
my_string[0] = 'h' # Raises TypeError: 'str' object does not support item assignment-----
TypeError: 'str' object does not support item assignment

Benefits of Immutable Objects

  1. Hashability and Dictionary Keys: Immutable objects can be used as keys in dictionaries because their hash value remains constant, ensuring that the key-value mapping is consistent.
  2. Memory Efficiency: Since immutable objects cannot change their value, Python can optimize memory usage. Reusing the same immutable object across the program whenever possible reduces memory overhead.
  3. Thread Safety: Immutability provides inherent thread safety. When multiple threads access the same immutable object, there’s no risk of data corruption due to concurrent modifications.
  4. Predictability and Debugging: With immutability, you can be confident that a given object’s value will not change unexpectedly, leading to more predictable and easier-to-debug code.
  5. Performance Optimization: Immutable objects facilitate certain performance optimizations, such as caching hash values for quick dictionary lookups.

Difference between Immutability and Mutability

Here we will discuss what is the key difference between mutability and immutability, with a proper example.

1. Mutability: Mutable objects are those objects that can be modified after their creation, to demonstrate mutability in Python we have a very popular data type which is the list.

Example:

Python3




my_list = [1, 2, 3]
print("Valid operation, modifying the first element of the list")
my_list[0] = 10
 
 

Output:

Valid operation, modifying the first element of the list
[10, 2, 3]

2. Immutability:

Immutability refers to the property of an object, that we can not change the object after we declare it.

Python3




my_string = "GeekGeek"
 
# Attempt to modify the string
my_string[0] = 'for'  # Raises TypeError: 'str' object does not support item assignment
#this will give an typeError
 
 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
my_string[0] = 'for' # Raises TypeError: 'str' object does not support item assignment
TypeError: 'str' object does not support item assignment

For More Details Read – Mutable vs Immutable Objects in Python

Ways to Deal with Immutability

  • String Slicing and Reassembling
  • String Concatenation
  • Using the join() method
  • Using String Formatting
  • Converting to Mutable Data Structures

1. String Slicing and Reassembling:

You can use slicing to extract parts of the string and then reassemble them as needed

Python3




name_1 = "Aarun"
 
name_2 = "T" + name_1[1:]
 
print("name_1 = ", name_1, "and name_2 = ", name_2)
 
 

Output:

name_1 =  Aarun and name_2 =  Tarun

2. String Concatenation:

Instead of modifying a string in place, you can concatenate strings to create a new one

Python




my_string = "Hello"
new_string = my_string + ", world!"  # Creates a new string with the concatenated result
print("This is our new string with the concatenated result")
print(new_string)
 
 

Output:

This is our new string with the concatenated result
Hello, world!

3. Using the join() method:

We can use the join() method if we have multiple strings to concatenate.

Python3




my_list = ["Hello", "world!"]
new_string = " ".join(my_list)  # Joins the list elements with a space separator
print("Joins the list elements with a space separator")
print(new_string)
 
 

Output:

Joins the list elements with a space separator
Hello world!

4. Using String Formatting

Here with the help of string formatting, we can insert the value and variable into the string

Python3




name = "Geeks"
new_string = "Hello {} ".format(name)
# Output: "My name is John and I am 30 years old."
print(new_string)
 
 

Output:

Hello Geeks

5. Converting to Mutable Data Structures

We can also convert the immutable data type to the mutable data type so that we can perform the desired operation on that data type.

Python




my_string = "Hello, world!"
my_list = list(my_string)
my_list[0] = 'h'
new_string = "".join(my_list)  # "hello, world!"
print(new_string)
 
 

Output:

hello, world!

In this article, we have covered mutable and immutable objects in Python. We saw examples of each with examples, we also checked key differences between mutable and immutable objects.

Immutability is very important in Python, as it helps in data safety and interpreter performance. The string data type is very common in Python programs hence they are immutable.

Similar Read:

Why do we Need Immutables in Python



Next Article
Python - Modify Strings

A

anshitaagarwal
Improve
Article Tags :
  • Python
  • python-string
Practice Tags :
  • python

Similar Reads

  • Python String
    A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
    6 min read
  • Why are Python Strings Immutable?
    Strings in Python are "immutable" which means they can not be changed after they are created. Some other immutable data types are integers, float, boolean, etc. The immutability of Python string is very useful as it helps in hashing, performance optimization, safety, ease of use, etc. The article wi
    5 min read
  • Python - Modify Strings
    Python provides an wide range of built-in methods that make string manipulation simple and efficient. In this article, we'll explore several techniques for modifying strings in Python. Start with doing a simple string modification by changing the its case: Changing CaseOne of the simplest ways to mo
    3 min read
  • Python String Manipulations

    • Python string length
      The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python s1 = "abcd" print(len(s1)) s2 = "" print(len(s2)) s3 = "a" print(len(s3)) [/GFGTABS]Outpu
      4 min read

    • String Slicing in Python
      String slicing in Python is a way to get specific parts of a string by using start, end and step values. It’s especially useful for text manipulation and data parsing. Let’s take a quick example of string slicing: [GFGTABS] Python s = "Hello, Python!" print(s[0:5]) [/GFGTABS]OutputHello Ex
      4 min read

    • How to reverse a String in Python
      Reversing a string is a common task in Python, which can be done by several methods. In this article, we discuss different approaches to reversing a string. One of the simplest and most efficient ways is by using slicing. Let’s see how it works: Using string slicingThis slicing method is one of the
      4 min read

    • Find Length of String in Python
      In this article, we will learn how to find length of a string. Using the built-in function len() is the most efficient method. It returns the number of items in a container. [GFGTABS] Python a = "geeks" print(len(a)) [/GFGTABS]Output5 Using for loop and 'in' operatorA string can be iterate
      2 min read

    • How to convert string to integer in Python?
      In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
      3 min read

  • Iterate over characters of a string in Python
    In this article, we will learn how to iterate over the characters of a string in Python. There are several methods to do this, but we will focus on the most efficient one. The simplest way is to use a loop. Let’s explore this approach. Using for loopThe simplest way to iterate over the characters in
    2 min read
  • Python String Concatenation and Comparison

    • String Comparison in Python
      Python supports several operators for string comparison, including ==, !=, <, <=, >, and >=. These operators allow for both equality and lexicographical (alphabetical order) comparisons, which is useful when sorting or arranging strings. Let’s start with a simple example to illustrate th
      3 min read

    • Python String Concatenation
      String concatenation in Python allows us to combine two or more strings into one. In this article, we will explore various methods for achieving this. The most simple way to concatenate strings in Python is by using the + operator. Using + OperatorUsing + operator allows us to concatenation or join
      3 min read

    • Python - Horizontal Concatenation of Multiline Strings
      Horizontal concatenation of multiline strings involves merging corresponding lines from multiple strings side by side using methods like splitlines() and zip(). Tools like itertools.zip_longest() help handle unequal lengths by filling missing values, and list comprehensions format the result. Using
      3 min read

    • String Repetition and spacing in List - Python
      We are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython']. U
      2 min read

    Python String Formatting

    • Python String Formatting - How to format String?
      String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in P
      10 min read

    • What does %s mean in a Python format string?
      In Python, the %s format specifier is used to represent a placeholder for a string in a string formatting operation. It allows us to insert values dynamically into a string, making our code more flexible and readable. This placeholder is part of Python's older string formatting method, using the % o
      3 min read

    • Python String Interpolation
      String Interpolation is the process of substituting values of variables into placeholders in a string. Let's consider an example to understand it better, suppose you want to change the value of the string every time you print the string like you want to print "hello <name> welcome to geeks for
      4 min read

    • Python Modulo String Formatting
      In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f -
      2 min read

    • How to use String Formatters in Python
      In Python, we use string formatting to control how text is displayed. It allows us to insert values into strings and organize the output in a clear and readable way. In this article, we’ll explore different methods of formatting strings in Python to make our code more structured and user-friendly. U
      3 min read

    • Python String format() Method
      format() method in Python is a tool used to create formatted strings. By embedding variables or values into placeholders within a template string, we can construct dynamic, well-organized output. It replaces the outdated % formatting method, making string interpolation more readable and efficient. E
      9 min read

    • f-strings in Python
      Python offers a powerful feature called f-strings (formatted string literals) to simplify string formatting and interpolation. f-strings is introduced in Python 3.6 it provides a concise and intuitive way to embed expressions and variables directly into strings. The idea behind f-strings is to make
      5 min read

  • Python String Methods
    Python string methods is a collection of in-built Python functions that operates on strings. Note: Every string method in Python does not change the original string instead returns a new string with the changed attributes. Python string is a sequence of Unicode characters that is enclosed in quotati
    6 min read
  • Python String Exercise
    Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove i’th character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences