Tuesday, October 14, 2008

Lists, tuples, dictionaries etc. in Python

I'm currently learning Django and found a useful reference explaining the different types of 'collection' structures in Python.

In brief:

List - contained in square brackets - like a PHP array - contents are editable.

Tuple - contained in round brackets - like a PHP array but contents are fixed (can't be edited). If only one item is specified, it must be followed by a comma.

Dictionary - contained in curly brackets - like an associative array in PHP

String - contained in quotes - can refer to individual characters by their position in the string like in a list/tuple

Iterator - a list temporarily created from an object to allow looping through each value using 'for ... in ...' syntax

With all of these, when referring to a specific item within the collection, you use square brackets.

No comments: