Accessing Elements – tuples¶
Let us see details related to operations on tuples. Unlike other collections (list
, set
, dict
) we have limited functions with tuple
in Python.
In [2]:
%%HTML
<iframe width="560" height="315" src="https://www.youtube.com/embed/fZ-QOUk-ia4?rel=0&controls=1&showinfo=0" frameborder="0" allowfullscreen></iframe>
tuple
is by definition immutable and hence we will not be able to add elements to a tuple or delete elements from a tuple.- Only functions that are available are
count
andindex
. count
gives number of times an element is repeated in a tuple.index
returns the position of element in a tuple.index
can take up to 3 arguments –element
,start
andstop
.
In [1]:
t = (1, 2, 3, 4, 4, 6, 1, 2, 3)
In [2]:
help(t)
In [3]:
t.count?
In [4]:
t.count(4)
Out[4]:
In [5]:
t.count(9)
Out[5]:
In [6]:
t.index?
In [7]:
t.index(2) # Scans all the elements
Out[7]:
In [8]:
t.index(2, 3) # Scans all the elements starting from 4th
Out[8]:
In [9]:
t.index(2, 3, 5) # throws ValueError, scans from 4th element till 5th element
In [10]:
t.index(9)
In [11]:
t.index(6, 3, 5) # throws ValueError, scans from 4th element till 5th element
In [12]:
t.index(6, 3, 6)
Out[12]:
In [ ]: