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]:
In [10]:
t[0]
Out[10]:
You can slice a tuple like you do in Lists.
In [11]:
# Slicing
t[1:]
Out[11]:
In [15]:
# Reversing a tuple
t[::-1]
Out[15]:
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
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
In [14]:
t.append(4)
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]:
In [19]:
# Number of values in a tuple
t.count('Three')
Out[19]:
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]:
In [22]:
# accessing the 2nd value in the tuple.
t[1]
Out[22]:
In [23]:
# accessing the values in the dictionary which is the 2nd element in our tuple.
t[1]['element']
Out[23]:
In [ ]: