Basic Data Types
Python is a dynamically typed language, which means that the Python interpreter infers
the type of an object at runtime. In comparison, compiled languages like C are generally
statically typed. In these cases, the type of an object has to be attached to the object before
compile time.
[ 18 ]
Integers
One of the most fundamental data types is the integer, or int:
In [ 1 ]: a = 10
type(a)
Out[1]: int
The built-in function type provides type information for all objects with standard and
built-in types as well as for newly created classes and objects. In the latter case, the
information provided depends on the description the programmer has stored with the class.
There is a saying that “everything in Python is an object.” This means, for example, that
even simple objects like the int object we just defined have built-in methods. For
example, you can get the number of bits needed to represent the int object in-memory by
calling the method bit_length:
In [ 2 ]: a.bit_length()
Out[2]: 4
You will see that the number of bits needed increases the higher the integer value is that
we assign to the object:
In [ 3 ]: a = 100000
a.bit_length()
Out[3]: 17
In general, there are so many different methods that it is hard to memorize all methods of
all classes and objects. Advanced Python environments, like IPython, provide tab
completion capabilities that show all methods attached to an object. You simply type the
object name followed by a dot (e.g., a.) and then press the Tab key, e.g., a.tab. This then
provides a collection of methods you can call on the object. Alternatively, the Python
built-in function dir gives a complete list of attributes and methods of any object.
A specialty of Python is that integers can be arbitrarily large. Consider, for example, the
googol number 10
100
. Python has no problem with such large numbers, which are
technically long objects:
In [ 4 ]: googol = 10 ** 100
googol
Out[4]: 100000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000L
In [ 5 ]: googol.bit_length()
Out[5]: 333
LARGE INTEGERS
Python integers can be arbitrarily large. The interpreter simply uses as many bits/bytes as needed to represent the
numbers.
It is important to note that mathematical operations on int objects return int objects. This
can sometimes lead to confusion and/or hard-to-detect errors in mathematical routines.