Understanding variables and objects in Python

In python everything is object and a variable is a reference to an object and each object has an identity or an ID associated with it:


#!/usr/bin/python3

x = 1

print(type(x))
print(id(x))

##################
#
# 139113568
##################

Remember, in python number, string, and tuple are immutable. But list, dictionary are mutable that means with the change of variable, the ID is changed.

x = 1
y = 1
print(type(x))
print(id(x))
print(type(y))
print(id(y))
if x == y:
print("True")
else:
print("False")

if x is y:
print("True")
else:
print("False")
##################
# see the last two lines, both are true
#
# 139113568
#
# 139113568
# True
# True
##################

a = dict(x = 1, y = 1)
print(type(a))
print(id(a))
b = dict(x = 1, y = 1)
print(id(b))
if a == b:
print("True")
else:
print("False")

if a is b:
print("True")
else:
print("False")

##################
# see the last two lines, one is true but the id is not same so it is false
#
# 3072650252
# 3072692524
# True
# False
##################

for i in range(0, 3):
print(i, "=", id(i))

##################
# 0 = 139113552
# 1 = 139113568
# 2 = 139113584
##################

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s