Chapter-8 Tuples PDF
Chapter-8 Tuples PDF
Chapter-8 Tuples PDF
By
Pankaj Singh - PGT (CS)
KV Bharatpur
• The tuples are very much similar to list. The elements are
accessed by their index number from 0 to len-1 in forward
direction and from -1, -2, … to –len in backward direction.
>>> t=(1,2,3,4)
>>> t[0] # will give 1
>>> t[3] # will give 4
>>> t[-1] # will also give 4
• len(tuple-name) is used to find the length of tuple
D
e
m
o
• Another Example:
>>> t=("Hello","this","is","a","pen")
>>> t # ('Hello', 'this', 'is', 'a', 'pen')
>>> for i in range (0, len(t)):
print ("Index ->",i,"Element ->",t[i])
• Joining tuples
>>> t1=(1,2,3)
>>> t2=(11,2,34,2)
>>> t3=t1+t2
>>> t3
(1, 2, 3, 11, 2, 34, 2)
• Tuple slices, like list-slice or string slices are the sub parts of
the tuple extracted out. We can use indexes of tuple elements
to create tuple slice as per following format:
seq = tuple [start : end]
seq = tuple [start : end : step]
t1 = (12,51,45,14,15,47,16,95,47,15,25)
>>> s1=t1[3:-4]
>>> s1 # will print (14, 15, 47, 16)
>>> s2=t1[1:len(t1):2]
>>> s2 # will print (51, 14, 47, 95, 15)
• We can compare two tuples without having to write code with loops for
it. We can use comparison operator for it
>>> t1=(2,3)
>>> t2=(2,3)
>>> t3=('2','3')
>>> t4=(5,2)
>>> t5=(2,3,4)
>>> t1==t2 # True
>>> t1==t3 # False
>>> t4<t2 # False
>>> t4>t5 # True
>>> t4==t5 # False
• Example:
>>> t1=(21,34,22)
>>> x,y,z = t1
>>> print (x)
21
>>> print (y)
34
>>> print (z)
22
20