Python Notes and Examples
← prev | next →     Top-level ToC     /types.html     (printable version)

Calling type(foo) returns the actual class object of which foo is an instance (that is, not foo’s class’s name (a string), but rather the actual class, which is itself an object).

type(3)          #=> int
type(3.1)        #=> float
type('hi')       #=> str
type([1,2])      #=> list
type((5,7))      #=> tuple
type({'a': 1})   #=> dict
type(set(8,9))   #=> set

Note that although you usually capitalize the names of your own types/classes, by Python convention those built-in types above are all named lowercase.

Ints automatically widen to floats. To convert between other types, pass the object to the new type’s constructor.

3 + 1.0       #=> 4.1 (a float)
3 + '1'       # Error
3 + int('1')  #=> 4
str(3) + '1'  #=> '31'