Tuples construct groups of objects.
They work exactly like lists, except that tuples are immutable.
Tuples are usually written as a series of items in parentheses.
The following table highlights common tuple operations.
A tuple is written as a series of objects, separated by commas and normally enclosed in parentheses.
An empty tuple is just a parentheses pair with nothing inside.
Operation | Interpretation |
---|---|
() | An empty tuple |
T = (0,) | A one-item tuple (not an expression) |
T = (0, 'Ni', 1.2, 3) | A four-item tuple |
T = 0, 'Ni', 1.2, 3 | Another four-item tuple (same as prior line) |
T = ('Bob', ('dev', 'mgr')) | Nested tuples |
T = tuple('test') | Tuple of items in an iterable |
T[i] T[i][j] T[i:j] len(T) | Index, index of index, slice, length |
T1 + T2 T * 3 | Concatenate, repeat |
for x in T: print(x) 'test' in T [x ** 2 for x in T] | Iteration, membership |
T.index('Ni') T.count('Ni') | Methods in 2.6, 2.7, and 3.X: search, count |
named_tuple('Emp', ['name', 'jobs']) | Named tuple extension type |