2.3. Python Data Containers

One of the reasons why Python is so highly regarded as a rapid development language is because of it’s advanced data containers and methods for working with them. Here we discuss the three most popular data container types (lists, tuples and dictionaries). The descriptions here are very basic, for more details, see the The Python documentation.

2.3.1. Lists

The list is the primary data structure used in Python. It holds a sequence of data elements. You can think of a list as an advanced array for now. The main differences between lists and arrays, which we see in Java and C, is that lists may contain data of differing data types and lists also have features such as list.append(), list.insert(), list.pop() and list.remove() (delete), which give lists additional functionality similar to linked lists in Java and C. The advance capabilities of lists allow one to construct common abstract data storage models such as stacks and queues in Python with very little effort or code.

In addition to being used to hold a sequence of data, lists also represents one of the most common iterator data types. An iterator is any sequence which may evaluated, one item at a time, in a for loop. The range() fuction, which we can use to create a definite loop, returns a list object.

Square brackets [] are used when we create or print a list:

>>> x = [1, 2, 3]
>>> print x
[1, 2, 3]
>>> x[1]     # list indexing
2
>>> x[:2]    # A list slice
[1, 2]
>>> x[-1]    # the last value in the list
3
>>> y = x[:]   # y is a copy of x
>>> y
[1, 2, 3]
>>> z = x[::-1]  # z is a copy of x in reverse order
>>> z
[3, 2, 1]
>>> z.sort()   # sort is a mutable operation on a list
>>> z
[1, 2, 3]

2.3.1.1. Examples of List Use

2.3.1.1.1. List Slicing

>>> x = ['first', 'second', 'third', 'forth']
>>> print x
['first', 'second', 'third', 'forth']

>>> x[2]
'third'

>>> x[2:]
['third', 'forth']

>>> x[:2]
['first', 'second']

>>> x[1:3]
['second', 'third']

>>> len(x)
4

2.3.1.1.2. Built-in list operators

in, +, *, del:

>>> x = ['one', 'two', 'three', 'four']
>>> x
['one', 'two', 'three', 'four']

>>> for a in x:
...     print a
...
one
two
three
four

>>> y = [5, 6]
>>> print x + y
['one', 'two', 'three', 'four', 5, 6]

>>> print x * 2
['one', 'two', 'three', 'four', 'one', 'two', 'three', 'four']

>>> del x[2]
>>> print x
['one', 'two', 'four']

2.3.1.1.3. List methods

list.append(), list.count(), list.extend(), list.index(), list.insert(), list.pop(), list.remove(), list.reverse(), list.sort():

>>> print x
['one', 'two', 'four']

>>> x.insert(2, 'three')
>>> print x
['one', 'two', 'three', 'four']

>>> x.append(['five', 'six'])
>>> print x
['one', 'two', 'three', 'four', ['five', 'six']]

>>> x.extend(['five', 'six'])
>>> print x
['one', 'two', 'three', 'four', 'five', 'six']

>>> x.count('four')
1

>>> x.index('five')
4

>>> x.pop()
'six'

>>> x['one', 'two', 'three', 'four', 'five']
>>> x.remove('two')
>>> print x
['one', 'three', 'four', 'five']

>>> x.reverse()
>>> print x
['five', 'four', 'three', 'one']

>>> x.sort()
>>> print x
['five', 'four', 'one', 'three']

2.3.2. Tuples

A tuple is a simplified list. Tuples are immutable, which means that after the tuple is created, it can not be modified (it is read only). Lists are more useful, but tuples are useful in certain situations and the implementation of tuples is a little leaner, so they can be faster. Use a tuple anytime you want to keep several values together as a single item and do not need to modify those values, at least not while they are stored inside the tuple.

Parenthesis () are used when we create or print a tuple:

>>> x = (1, 2, 3)
>>> x
(1, 2, 3)
>>> x[1]
2
>>> x[1:]
(2, 3)

An example of when you might want to use a tuple is to group several values together for storage and later use. The tuple is often used together with lists and dictionaries to achieve this. In the following example, we show grouping some information about a client network connection and then appending that data to a list. The list contains an entry for each client. What ever code later retrieves this data can take a single item from the list, which is a tuple, and then extract the individual values from the tuple.

my_data = (host_name, ip_address, socket, message)
clients.append(my_data)

2.3.3. Dictionaries

A dictionary provides a way to associate key words with a value. Each key, which is usually a string, must be unique. The keys are also immutable. Items in the dictionary may removed with the dict.del() statement.

Curly brackets {} are used when we create or print a dictionary and the key and value are separated using the colon `` : `` .

>>> d = {}          # an empty dictionary
>>> d['x'] = 5      # add a couple values
>>> d['y'] = 3
>>> d
{'y': 3, 'x': 5}
>>> e = {'a': 2, 'b': 6} # start e with some initial data
>>> e
{'a': 2, 'b': 6}
>>> del e['a']
>>> e
{'b': 6}

Dictionary examples:

>>> d = {'one':1, 'two':2}
>>> d['one']
1

>>> d['one'] = 3
>>> d['one']
3

>>> d
{'two': 2, 'one': 3}

>>> d.items()
[('two', 2), ('one', 3)]

>>> d.keys()
['two', 'one']

>>> d.values()
[2, 3]

>>> d.has_key('two')
True

>>> d = {'one':1, 'two':2}
>>> e = d.copy()
>>> print e
{'two': 2, 'one': 1}

>>> f = d
>>> print f
{'two': 2, 'one': 1}

>>> d.update({'three':3})
>>> print d
{'three': 3, 'two': 2, 'one': 1}

>>> print e
{'two': 2, 'one': 1}

>>> print f
{'three': 3, 'two': 2, 'one': 1}