Python Notes and Examples

Types

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 object).

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

def f(x): pass
type(f)          # => function

type(max)        # => builtin_function_or_method

import sys
type(sys)        # => module

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'       # throws TypeError
3 + int('1')  # => 4
str(3) + '1'  # => '31'