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:
>>> a = 3
>>> print type(a)
<type 'int'>
>>> a = 3.14
>>> print type(a)
<type 'float'>
>>> a = 'hello python'
>>> print type(a)
<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:
>>> a = 'this is an ASCII string'
>>> b = u'This is a Unicode string'
>>> 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:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
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:
>>> for i in [3, 'hello']:
... print str(i), repr(i)
...
3 3
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.
>>> for i in 'hello':
... print i
...
h
e
l
l
o
list
The main methods of a Python list are append, insert, and delete:
>>> a = [1, 2, 3]
>>> print type(a)
<type 'list'>
>>> a.append(8)
>>> a.insert(2, 7)
>>> del a[0]
>>> print a
[2, 7, 3, 8]
>>> print len(a)
4
Lists can be sliced:
>>> print a[:3]
[2, 7, 3]
>>> print a[1:]
[7, 3, 8]
>>> print a[-2:]
[3, 8]
and concatenated:
>>> a = [2, 3]
>>> b = [5, 6]
>>> print a + b
[2, 3, 5, 6]
A list is iterable; you can loop over it:
>>> a = [1, 2, 3]
>>> for i in a:
... print i
...
1
2
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:
>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> for x in a:
... if x % 2 == 0:
... b.append(x * 3)
...
>>> b
[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:
>>> a = [1, 2, 3, 4, 5]
>>> b = [x * 3 for x in a if x % 2 == 0]
>>> b
[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.
>>> a = (1, 2, 3)
So while this works for a list:
>>> a = [1, 2, 3]
>>> a[1] = 5
>>> print a
[1, 5, 3]
the element assignment does not work for a tuple:
>>> a = (1, 2, 3)
>>> print a[1]
2
>>> a[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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:
>>> a = (1)
>>> print type(a)
<type 'int'>
>>> a = (1, )
>>> print type(a)
<type 'tuple'>
Tuples are very useful for efficient packing of objects because of their immutability, and the brackets are often optional:
>>> a = 2, 3, 'hello'
>>> x, y, z = a
>>> print x
2
>>> print z
hello
dict
A Python dict
-ionary is a hash table that maps a key object to a value object. For example:
>>> a = {'k':'v', 'k2':3}
>>> a['k']
v
>>> a['k2']
3
>>> a.has_key('k')
True
>>> a.has_key('v')
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:
>>> a = dict(k='v', h2=3)
>>> a['k']
v
>>> print a
{'k':'v', 'h2':3}
Useful methods are has_key
, keys
, values
and items
:
>>> a = dict(k='v', k2=3)
>>> print a.keys()
['k', 'k2']
>>> print a.values()
['v', 3]
>>> print a.items()
[('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
:
>>> a = [1, 2, 3]
>>> del a[1]
>>> print a
[1, 3]
>>> a = dict(k='v', h2=3)
>>> del a['h2']
>>> print a
{'k':'v'}
Internally, Python uses the hash
operator to convert objects into integers, and uses that integer to determine where to store the value.
>>> hash("hello world")
-1500746465