Tuples

Tuples can contain an array of objects but they are immutable meaning the data cannot be changed. Tuples are like immutable lists. Main use case for Tuples are those that need not be changed like list of week days etc...

Tuples ensures data integrity.

Creating Tuples


In [10]:
t1 = (1,2,3)
type(t1)


Out[10]:
tuple

In [12]:
# Tuples can contain mixed object types
t2 = (1,'two',['three','four','five'],{'key':'value'})
print(type(t2))
t2


<class 'tuple'>
Out[12]:
(1, 'two', ['three', 'four', 'five'], {'key': 'value'})

In [14]:
t2[0]


Out[14]:
1

In [3]:
t2[2][2]


Out[3]:
'five'

In [4]:
t2[3]['key']


Out[4]:
'value'

In [21]:
t3 = (1)
t3


Out[21]:
1

In [29]:
t3 = (1,2,3)
t4 = ('a','b')
t3 + t4


Out[29]:
(1, 2, 3, 'a', 'b')

In [31]:
t3 * 5


Out[31]:
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

Immutability


In [8]:
# tuples are immutable

t2[0]=2 # this will create an error
t2


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-dc9eb5c4fb85> in <module>()
----> 1 t2[0]=2
      2 t2

TypeError: 'tuple' object does not support item assignment

In [7]:
# although tuples are immutable if the object in the tuple is mutable then data can be changed
t2[3]['key']='no value'
t2


Out[7]:
(1, 'two', ['three', 'four', 'five'], {'key': 'no value'})

In [9]:
t2[2].append('six')
t2


Out[9]:
(1, 'two', ['three', 'four', 'five', 'six'], {'key': 'no value'})

Indexing and Slicing


In [15]:
t2[0:2]


Out[15]:
(1, 'two')

In [16]:
t2[-1]


Out[16]:
{'key': 'value'}

In [17]:
len(t2)


Out[17]:
4

In [18]:
t2[::-1]


Out[18]:
({'key': 'value'}, ['three', 'four', 'five'], 'two', 1)

Tuples Methods


In [19]:
# index gives the position of the element
t2.index(1)


Out[19]:
0

In [20]:
# count of elements present in the tuple
t2.count(1)


Out[20]:
1

In [24]:
# cannot delete tuple element
print(t2)
del(t2[2])
t2


(1, 'two', ['three', 'four', 'five'], {'key': 'value'})
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-e51ca2d3176d> in <module>()
      1 # delete tuple element
      2 print(t2)
----> 3 del(t2[2])
      4 t2

TypeError: 'tuple' object doesn't support item deletion

In [26]:
t2
del(t2)
t2


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-c34fbcd134d8> in <module>()
----> 1 t2
      2 del(t2)
      3 t2

NameError: name 't2' is not defined

Iterating through a Tuple


In [23]:
for name in ('John','Jack'):
    print ("Hello ", name)


Hello  John
Hello  Jack

Tuple Membership Test


In [27]:
t3 = ('a','b','c','d')
'a' in t3


Out[27]:
True

In [28]:
'z' in t3


Out[28]:
False