Comparing the type of two objects in python

Sunday, July 1, 2012

This code illustrates how to compare the type of any two objects in python with a simple example.

Listing 1: type_comparison.py

"""
   Code to check an object's type
   Author: S.Prasanna
"""

print "type(list) = %s" % list
print "type(dict) = %s" % dict
print "type(tuple) = %s" % tuple

list_obj = [1,2]
dict_obj = {1:1, 2:2}
tuple_obj = (1,2)

print "type(%s) == %s is %s" % (list_obj, list, (type(list_obj) == list))
print "type(%s) == %s is %s" % (dict_obj, dict, (type(dict_obj) == dict))
print "type(%s) == %s is %s" % (tuple_obj, dict, (type(tuple_obj) == tuple))
print "type(%s) == %s is %s" % (list_obj, tuple, (type(list_obj) == tuple))
Syntax highlighter: Pygments

Sample Output:

>>>
type(list) = <type 'list'>
type(dict) = <type 'dict'>
type(tuple) = <type 'tuple'>
type([1, 2]) == <type 'list'> is True
type({1: 1, 2: 2}) == <type 'dict'> is True
type((1, 2)) == <type 'dict'> is True
type([1, 2]) == <type 'tuple'> is False
>>>

No comments:


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.