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.
In [10]:
t1 = (1,2,3)
type(t1)
Out[10]:
In [12]:
# Tuples can contain mixed object types
t2 = (1,'two',['three','four','five'],{'key':'value'})
print(type(t2))
t2
Out[12]:
In [14]:
t2[0]
Out[14]:
In [3]:
t2[2][2]
Out[3]:
In [4]:
t2[3]['key']
Out[4]:
In [21]:
t3 = (1)
t3
Out[21]:
In [29]:
t3 = (1,2,3)
t4 = ('a','b')
t3 + t4
Out[29]:
In [31]:
t3 * 5
Out[31]:
In [8]:
# tuples are immutable
t2[0]=2 # this will create an error
t2
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]:
In [9]:
t2[2].append('six')
t2
Out[9]:
In [15]:
t2[0:2]
Out[15]:
In [16]:
t2[-1]
Out[16]:
In [17]:
len(t2)
Out[17]:
In [18]:
t2[::-1]
Out[18]:
In [19]:
# index gives the position of the element
t2.index(1)
Out[19]:
In [20]:
# count of elements present in the tuple
t2.count(1)
Out[20]:
In [24]:
# cannot delete tuple element
print(t2)
del(t2[2])
t2
In [26]:
t2
del(t2)
t2
In [23]:
for name in ('John','Jack'):
print ("Hello ", name)
In [27]:
t3 = ('a','b','c','d')
'a' in t3
Out[27]:
In [28]:
'z' in t3
Out[28]: