Thursday, February 9, 2017

Objects and Values

Let’s assign same values to two different variables.
>>>a = ‘Gibson’
>>>b = ‘Gibson’
Both a and b refer to a string, but we don’t know whether day refer to same string. In one case, a and b refer to two different objects that have the same value while in the second case, they refer to the same object.
In order to test whether two variables refer to the same object, you can use the ‘is’ operator.
>>> a = 'Gibson'
>>> b = 'Gibson'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to it. But when you create two lists, you get two objects:
>>> d = [1, 2, 3]
>>> e = [1, 2, 3]
>>> d is e
False
In case of lists we would say that these two lists are equivalent and the reason for that is they have same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent but if they are equivalent, they are not necessarily identical.
Difference between object and the value.

So far we’ve used term ‘object’ and therm ‘value’ interchangeably, but it is more precise to say that an object has a value. If you execute a = [1, 2, 3], a refers to a list whose value is a particular sequence of elements. If second or another list has the same elements, we say that it has the same values. 

No comments:

Post a Comment