Tuples

  • We saw that lists and strings have many common properties, such as indexing and slicing operations. There is also another standard sequence data type: the tuple.

  • A tuple consists of a number of values separated by commas, for instance:

t = 12345, 54321, 'hello!'
print( t[0])
print( t)

# Tuples may be nested
u = t, (1, 2, 3, 4, 5)
print(u)

# Tuples can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v[0][2] = 5
print(v)

# Tuples are immutable:
t[0] = 88888 #throws an error
12345
(12345, 54321, 'hello!')
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
([1, 2, 5], [3, 2, 1])





TypeErrorTraceback (most recent call last)

<ipython-input-5-610e7c5d7e14> in <module>()
     13 
     14 # Tuples are immutable:
---> 15 t[0] = 88888


TypeError: 'tuple' object does not support item assignment

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). For example:

Addding Elements to a Tuple

We can add new element to tuple using + operator.

Tuple Assignment

If we want to interchange (swap) any two variable values, we have to use temporary variable. For example:

But in python, tuple assignment is more elegant:

Slicing

  • Slicing in tuple is similar to list or string slicing

  • Syntax of tuple slicing is tuple[start : stop : steps].

  • which means that slicing will start from index start will go up to stop in step of steps.

  • Default value of start is 0, stop is last index of list and for step it is 1.

Other Tuple Methods

cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

len(s)

This method returns number of elements in the given tuple.

max(iterable)

It returns its largest item in the tuple.

min(iterable)

It returns its least item in the tuple.

Last updated

Was this helpful?