Python: Structured Types

Note: Lines beginning with ">>>" and "..." indicate input to Python (these are the default prompts of the interactive interpreter). Everything else is output from Python.

The following example assigns a list with four elements to the variable foo. The elements are:

The elements in the sublist are:

After the assignment, a few simple statements demonstrate how easy it is to handle such types and parts of it, without the need of additional syntax elements or awkward constructs such as pointers or references. Using lists and other types in Python is very natural and intuitive.

>>> foo = [42, 'hurz', lambda x: x**2, [47, '11']]
>>> print foo
[42, 'hurz', <function <lambda> at 0x8119e8c>, [47, '11']]
>>> print foo[3]
[47, '11']
>>> print foo[2](3)
>>> foo[3][0] = 99
>>> print foo
[42, 'hurz', <function <lambda> at 0x8119e8c>, [99, '11']]
>>> for i in foo:
...     print i, "--", type(i)
42 -- <type 'int'>
hurz -- <type 'string'>
<function <lambda> at 0x8119e8c> -- <type 'function'>
[99, '11'] -- <type 'list'>

As you can see, every value has a well-defined type in Python. In fact, everything in Python has a type, including modules, functions, classes, instances and even types themselves:

>>> print type(types)
<type 'module'>
>>> print type(type(1))
<type 'type'>

Python does not perform a lot of automatic type conversions (so-called coercions). Most of them happen for arithmetic types: integers are converted to long integers if necessary, or to floats or complex numbers. Another notable exception is the "print" statement, which converts its arguments to strings in order to print them.

In most other cases, you have to specify the conversion explicitely, otherwise you'll get an error (such as when you try to add a string to an integer). This is a good thing, because it prevents you from common programming errors which could easily sneak into your code and stay there undiscovered for a long time, and are difficult to hunt down.

[HTML 4.01]