Types

Python is a dynamically typed language, meaning that variables do not have a type and therefore do not have to be declared. Values, on the other hand, do have a type. You can query a variable for the type of value it contains:

  1. >>> a = 3
  2. >>> print type(a)
  3. <type 'int'>
  4. >>> a = 3.14
  5. >>> print type(a)
  6. <type 'float'>
  7. >>> a = 'hello python'
  8. >>> print type(a)
  9. <type 'str'>

Python also includes, natively, data structures such as lists and dictionaries.

str

Python supports the use of two different types of strings: ASCII strings and Unicode strings. ASCII strings are delimited by ‘…’, “…” or by ‘..‘ or “””…”””. Triple quotes delimit multiline strings. Unicode strings start with a u followed by the string containing Unicode characters. A Unicode string can be converted into an ASCII string by choosing an encoding for example:

  1. >>> a = 'this is an ASCII string'
  2. >>> b = u'This is a Unicode string'
  3. >>> a = b.encode('utf8')

After executing these three commands, the resulting a is an ASCII string storing UTF8 encoded characters. By design, web2py uses UTF8 encoded strings internally.

It is also possible to write variables into strings in various ways:

  1. >>> print 'number is ' + str(3)
  2. number is 3
  3. >>> print 'number is %s' % (3)
  4. number is 3
  5. >>> print 'number is %(number)s' % dict(number=3)
  6. number is 3

The last notation is more explicit and less error prone, and is to be preferred.

Many Python objects, for example numbers, can be serialized into strings using str or repr. These two commands are very similar but produce slightly different output. For example:

  1. >>> for i in [3, 'hello']:
  2. ... print str(i), repr(i)
  3. ...
  4. 3 3
  5. hello 'hello'

For user-defined classes, str and repr can be defined/redefined using the special operators __str__ and __repr__. These are briefly described later on; for more, refer to the official Python documentation[pydocs] . repr always has a default value.

Another important characteristic of a Python string is that, like a list, it is an iterable object.

  1. >>> for i in 'hello':
  2. ... print i
  3. ...
  4. h
  5. e
  6. l
  7. l
  8. o

list

The main methods of a Python list are append, insert, and delete:

  1. >>> a = [1, 2, 3]
  2. >>> print type(a)
  3. <type 'list'>
  4. >>> a.append(8)
  5. >>> a.insert(2, 7)
  6. >>> del a[0]
  7. >>> print a
  8. [2, 7, 3, 8]
  9. >>> print len(a)
  10. 4

Lists can be sliced:

  1. >>> print a[:3]
  2. [2, 7, 3]
  3. >>> print a[1:]
  4. [7, 3, 8]
  5. >>> print a[-2:]
  6. [3, 8]

and concatenated:

  1. >>> a = [2, 3]
  2. >>> b = [5, 6]
  3. >>> print a + b
  4. [2, 3, 5, 6]

A list is iterable; you can loop over it:

  1. >>> a = [1, 2, 3]
  2. >>> for i in a:
  3. ... print i
  4. ...
  5. 1
  6. 2
  7. 3

The elements of a list do not have to be of the same type; they can be any type of Python object.

There is a very common situation for which a list comprehension can be used. Consider the following code:

  1. >>> a = [1, 2, 3, 4, 5]
  2. >>> b = []
  3. >>> for x in a:
  4. ... if x % 2 == 0:
  5. ... b.append(x * 3)
  6. ...
  7. >>> b
  8. [6, 12]

This code clearly processes a list of items, selects and modifies a subset of the input list, and creates a new result list, and this code can be entirely replaced with the following list comprehension:

  1. >>> a = [1, 2, 3, 4, 5]
  2. >>> b = [x * 3 for x in a if x % 2 == 0]
  3. >>> b
  4. [6, 12]

tuple

A tuple is like a list, but its size and elements are immutable, while in a list they are mutable. If a tuple element is an object, the object attributes are mutable. A tuple is delimited by round brackets.

  1. >>> a = (1, 2, 3)

So while this works for a list:

  1. >>> a = [1, 2, 3]
  2. >>> a[1] = 5
  3. >>> print a
  4. [1, 5, 3]

the element assignment does not work for a tuple:

  1. >>> a = (1, 2, 3)
  2. >>> print a[1]
  3. 2
  4. >>> a[1] = 5
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. TypeError: 'tuple' object does not support item assignment

A tuple, like a list, is an iterable object. Notice that a tuple consisting of a single element must include a trailing comma, as shown below:

  1. >>> a = (1)
  2. >>> print type(a)
  3. <type 'int'>
  4. >>> a = (1, )
  5. >>> print type(a)
  6. <type 'tuple'>

Tuples are very useful for efficient packing of objects because of their immutability, and the brackets are often optional:

  1. >>> a = 2, 3, 'hello'
  2. >>> x, y, z = a
  3. >>> print x
  4. 2
  5. >>> print z
  6. hello

dict

A Python dict-ionary is a hash table that maps a key object to a value object. For example:

  1. >>> a = {'k':'v', 'k2':3}
  2. >>> a['k']
  3. v
  4. >>> a['k2']
  5. 3
  6. >>> a.has_key('k')
  7. True
  8. >>> a.has_key('v')
  9. False

Keys can be of any hashable type (int, string, or any object whose class implements the __hash__ method). Values can be of any type. Different keys and values in the same dictionary do not have to be of the same type. If the keys are alphanumeric characters, a dictionary can also be declared with the alternative syntax:

  1. >>> a = dict(k='v', h2=3)
  2. >>> a['k']
  3. v
  4. >>> print a
  5. {'k':'v', 'h2':3}

Useful methods are has_key, keys, values and items:

  1. >>> a = dict(k='v', k2=3)
  2. >>> print a.keys()
  3. ['k', 'k2']
  4. >>> print a.values()
  5. ['v', 3]
  6. >>> print a.items()
  7. [('k', 'v'), ('k2', 3)]

The items method produces a list of tuples, each containing a key and its associated value.

Dictionary elements and list elements can be deleted with the command del:

  1. >>> a = [1, 2, 3]
  2. >>> del a[1]
  3. >>> print a
  4. [1, 3]
  5. >>> a = dict(k='v', h2=3)
  6. >>> del a['h2']
  7. >>> print a
  8. {'k':'v'}

Internally, Python uses the hash operator to convert objects into integers, and uses that integer to determine where to store the value.

  1. >>> hash("hello world")
  2. -1500746465