# tuples are like lists, but immutable >>> l = [ 0, 1, 2 ] >>> type(l) Out[1]: list >>> t = ( 0, 1, 2 ) >>> type(t) Out[1]: tuple >>> l[0] = 'a' >>> l Out[1]: ['a', 1, 2] # trying to change a tuple causes an error >>> t[0] = 'a' Traceback (most recent call last): File "/Users/guestuser/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2721, in run_code exec code_obj in self.user_global_ns, self.user_ns File "", line 1, in t[0] = 'a' TypeError: 'tuple' object does not support item assignment # typical template for iterating over a sequence using indexing >>> for k in range(len(l)): … print(str(k) + "\t" + str(l[k])) 0 a 1 1 2 2 # python function that bundles index and value as a tuple >>> list(enumerate(l)) Out[1]: [(0, 'a'), (1, 1), (2, 2)] >>> for (k,v) in enumerate(l): ... print(str(k) + "\t" + str(v)) 0 a 1 1 2 2 # python function that bundles multiple lists into one lists of tuples >>> zip(l, t) Out[1]: [('a', 0), (1, 1), (2, 2)] >>> for (lv,tv) in zip(l, t): … print(str(lv) + "\t" + str(tv)) a 0 1 1 2 2 # fun with tuples --- swapping! >>> a = 12 >>> b = 'z' >>> print(str(a) + '\t' + str(b)) 12 z # swapping "manually" >>> c = a >>> a = b >>> b = c >>> print(str(a) + '\t' + str(b)) z 12 # swapping using tuples >>> (b, a) = (a, b) >>> print(str(a) + '\t' + str(b)) 12 z # representing "data" as a tuple >>> color = (128, 255, 0) # using index to get specific "field" >>> color[0] Out[1]: 128 >>> colorList = [ color, (0, 0, 0), (255, 255, 255) ] >>> colorList[0] Out[1]: (128, 255, 0) >>> from collections import namedtuple >>> Color = namedtuple('Color', 'red, green, blue') >>> color = Color(128, 255, 0) >>> print(color) Color(red=128, green=255, blue=0) # can use name to get data >>> color.red Out[1]: 128 # or can still use index if you want >>> color[0] Out[1]: 128