Change the ID of an Immutable String in Python



In Python, strings are immutable, which means once the string is created, it cannot be changed. Because of this immutability, any operation that tries to modify the string results in creating a new string object with a different identity.

Every object in Python has a unique identity, which can be accessed by using the built-in id() function. In this article, we are going to learn about changing the id of an immutable string in Python.

We cannot directly change the ID of the immutable string, but by reassigning or modifying it, we can create a new string and assign it to the same variable, which results in a different ID. Let's explore how this works with examples.

By Reassigning the Value

Since the string is immutable in Python, if we reassign a value to an existing string literal, the previous one will be discarded and the value will be assigned to a new memory location, thus changing the id.

Example

In the following example, we are going to reassign the string.

demo = "WELCOME"
print("Before Reassignment:", id(demo))
demo = "TO TP"
print("After Reassignment:", id(demo))

Output

The output of the above program is as follows -

Before Reassignment: 140411616532192
After Reassignment: 140411616536896

Using Concatenation

Concatenation is nothing but the joining of two or more strings (or sequences) end-to-end to form a combined string. If we concatenate an existing string with a new string, similar to the case of reassignment a the newly formed string is stored in a new memory location, discarding the old one. This too, results in a change of the id of a string.

Example

Consider the following example, where we are going to perform concatenation on the string.

demo = "TP"
print("Original ID:", id(demo))
demo += "TutorialsPoint"
print("After concatenation:", id(demo))

Output

The output of the above program is as follows -

Original ID: 140200443926336
After concatenation: 140200444093616

Using Python upper() Method

The Python upper() method is used to convert all the lowercase characters in a string into uppercase and returns the result in a new string.

Syntax

Following is the syntax for the Python upper() method -

str.upper()

Example

Following is an example where we are going to use the upper() method and observe the output.

demo = "tutorialspoint"
print("Before upper() Method:", id(demo))
demo = demo.upper()
print("After upper() Method:", id(demo))

Output

Following is the output of the above program -

Before upper() Method: 139877156152496
After upper() Method: 139877155693744
Updated on: 2025-04-16T17:26:18+05:30

897 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements