Mohit Aphale
Mohit Aphale

Reputation: 51

Please Explain the Difference between these two Codes

Code 1

nums = [1, 2, 3]
tri = nums
nums.append(4)
print(tri)       //this prints [1, 2, 3, 4]

Code 2

num = 9
num2 = num
num = 12
print num2       // this prints 9 **BUT I expected 12 like abouve code**

My Ques is Why there is a Difference between these two outputs when the the Procedure and Assignments are almost Similar ?

Upvotes: 1

Views: 128

Answers (3)

Lakmal
Lakmal

Reputation: 1

Code 1 your using Tuple. Tuples are reference type Data. (Arrays, Tuple, Class)

Code 2 is Your using Integer. It's Value Type Data.

Value Type always copy value to another memory location.

But Reference data type always Replace value to memory location.

This Concept comes with Object Oriented Programming.

Upvotes: -1

Senduran
Senduran

Reputation: 68

nums is a list, so it is copied by reference and the num is copied by value.

you can use tri = nums[:] to copy the nums by value

Upvotes: 0

chepner
chepner

Reputation: 531165

In your first example, nums and tri refer the same object. The append method modifies the reference object in place, so both nums and tri continue to refer to the same (modified) object.

In your second example, num is set to a completely new object (12); num2 continues to refer to the object (9) that num referred to before you changed its value.

Upvotes: 4

Related Questions