Tuples

Tuples are like Lists, but they are immutable, means once we assign a value to a tuple we cannot change it or it cannot be changed.

Tuple values are enclosed in (). Tuple can hold values of different types.

You can think of them as constant arrays.


In [8]:
t = (1,2.0,'Three')

In [9]:
t


Out[9]:
(1, 2.0, 'Three')

In [10]:
t[0]


Out[10]:
1

You can slice a tuple like you do in Lists.


In [11]:
# Slicing
t[1:]


Out[11]:
(2.0, 'Three')

In [15]:
# Reversing a tuple
t[::-1]


Out[15]:
('Three', 2.0, 1)

Remember that we are slicing the tuple for display purpose only. We cannot change a tuple.

Now lets try to change the value in a tuple and see what happens.


In [12]:
t[0] = 10


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-eaf187d38884> in <module>()
----> 1 t[0] = 10

TypeError: 'tuple' object does not support item assignment

So we have an error saying that tuple do not support item assignment.

By this constraint tuples are of fixed size. A Tuple cannot grow, which means we cannot add an item once a tuple is created.


In [13]:
t[3] = 4


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-200707f74b8d> in <module>()
----> 1 t[3] = 4

TypeError: 'tuple' object does not support item assignment

In [14]:
t.append(4)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-e8bd1632f9dd> in <module>()
----> 1 t.append(4)

AttributeError: 'tuple' object has no attribute 'append'

Basic functions for tuples

There are only two functions available for tuples count() and index().

The index() returns the index of the value supplied and the count() returns the number of time a value appears in a tuple.


In [16]:
# Finding the index of the value: 2.0
t.index(2.0)


Out[16]:
1

In [19]:
# Number of values in a tuple
t.count('Three')


Out[19]:
1

A tuple value can be any python object, it can be a List, dictonary etc.


In [20]:
t = ('hello', {'element': 'Oxygen', 'weight': 15.999}, 1234)

In [21]:
t


Out[21]:
('hello', {'element': 'Oxygen', 'weight': 15.999}, 1234)

In [22]:
# accessing the 2nd value in the tuple.
t[1]


Out[22]:
{'element': 'Oxygen', 'weight': 15.999}

In [23]:
# accessing the values in the dictionary which is the 2nd element in our tuple.
t[1]['element']


Out[23]:
'Oxygen'

In [ ]: