Type Error

Types in Python

A type in Python can be thought of as the specification for a category of related data. Though we as programmers can technically define own types, they tend to fall into a set of pre-defined categories. So, for now, let's focus on the most common types that are built into the Python language. Specifically, they are:

For further clarification, here are some pieces of data and their associated types:

>>> 25 # an int
>>> 3.14 # a float
>>> "Neigh!" # a string
>>> [2, 13, 10] # a list (containing three objects of type int)
>>> (5, 0, 7) # a tuple --- much like a list, but it can't ever be modified

When you call a function or use an operator in Python, it typically expects to be given parameters of a specific type. For example, the multiplication operator (*) expects to be given two parameters of numeric type, that is, the types int and float:

>>> 49401314 * 150
7410197110
>>> 1187228.3001583007 * 7
8310598.101108105

Type Errors in Python

A TypeError occurs in Python when you attempt to call a function or use an operator on something of the incorrect type. For example, let's see what happens when we try and add together two incompatible types:

>>> 2 + "two"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Because the plus operator (+) expected two numeric parameters, Python throws a TypeError, telling us that one of our parameters was of the incorrect type. Let's take a look at another example:

>>> myVar = 30
>>> myVar[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

Because we can't access int type objects by index, as we can with list, tuple, or string type objects, Python once again throws a TypeError. In PyLearn, the message would be displayed as follows:

>>> myVar[1]
TypeError: Can't access an index for an object of type -- 'int'.

In general, if you've encountered a TypeError in Python, take a moment to verify that the data you are operating on is actually of the type you expected it to be. To do so, simply call the built-in type() function on the questionable data, and Python will gladly report its type to you:

>>> type("lovely")
<type 'str'>