Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

When I enter the below code:

x=[1,2,4]

print(x)

print("x",id(x))

x=[2,5,3]

print(x)

print("x",id(x))

I will get the output:

[1, 2, 4]

x 47606160

[2, 5, 3]

x 47578768

In the event that list is mutable, why it gives 2 memory address while changing the list x? 

1 Answer

0 votes
by (26.4k points)

You didn't transform (change) the list object referred to by x with this line: 

x=[2,5,3]

All things considered, that line makes another list object and afterward reassigns the variable x to it. Thus, x currently references the new item, and id(x) gives an unexpected number in comparison to previously:

>>> x=[1,2,4]  # x references the list object [1,2,4]

>>> x

[1, 2, 4]

>>> x=[2,5,3]  # x now references an entirely new list object [2,5,3]

>>> x

[2, 5, 3]

>>>

Interested to learn python in detail? Come and Join the python course.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 4, 2021 in Python by Rekha (2.2k points)

Browse Categories

...