Main Content

Collections in Python - list tuple dict and string.

Archive - Originally posted on "The Horse's Mouth" - 2013-03-04 16:34:35 - Graham Ellis

All the languages that we teach have "collection" variables - single names under which a series of values is stored, keyed or indexed in some way. There are four such types in Python

Lists ... starting off with index position 0, and alterable within the stucture as the program runs. You may erroneously associate such a structure with the word "array" - technically incorrect because an array is usually at successive memory loactions, whereas a list isn't necessarily so. At the cost of a little speed in simple operations, the structure of a list allows it to be extended once it's been created, and allows elements to be removed from and inserted into the middle without having to move up all the rest of the data.

Tuples ... also indexed from position 0, but NOT alterable within the stucture as the program runs. If you want to change a tuple, you have to get rebuild and replace the whole collection - quite straightforward, but inefficient. On the other hand, if you set up data in a single statement and then don't want to change it, a tuple gives you a speed advantage.

Dicts ... keyed by name / object rather than by position number. Dicts are sometimes compared to database tables with two columns (a key and value), and at other times to PHP's associative array, or to hashes in Perl. That last's probably the closest comparison and dicts are defined for very fast access to data via keys, at the expense of not being sortable.

Strings ... are a collection of characters. Like Tuples, once set up you're required to rebuild the whole of a string if you change it.

You can create any of these variables (objects) using its constructor, or use shorthands if you prefer:
  [] for list
  {} for dict
  () for tuple
  "" for string (or '' or triple quotes)
and you can then reference individual elements within any of the collections using [].

Examples of all the syntax - [here] - my demonstration from last week's Python training class.