Tuples :
Tuples are defined by enclosing the elements in parentheses () and is immutable in
nature.
Example :
t=() --→ empty tuple
t = (5,) --→ tuple containing single element
t = (1, 2, 3) --→ tuple containing elements of same data type
t = (‘a’, 1, 2.5, 2.0+3.5j) --→ tuple containing elements belonging to different
datatype
Note :
t = (1) --→ is an integer not a tuple.
Where as t1 = (3,) --→ is a tuple
Creating a tuple
Creating tuple form an existing sequence
variable_name = tuple(sequence)
here a sequence can be a list,dictionary,set,string and range() function
example
Creating tuple by taking user input
method 1 : variable_name = tuple(input(‘ Input message goes here’) )
method 2 : variable_name = eval(input(‘ Input message goes here’) )
Note the difference between the two in first method the value is passed as string
which is converted into tuple whereas in second method the value is passed in form of
tuple.
Accessing tuple elements
• Elements of tuple can be accessed through indexing
• Syntax : tuple_name[index]
eg tup = (1,’a’,3,4.5)
-4 -3 -2 -1 ←-- backward indexing
1 ‘a’ 3 4.5
0 1 2 3
--→ forward indexing
so,
Traversing a Tuple
Traversing is visiting elements of the tuple.
Tuple operation
• Concatenation
• Replication
• max()
• min()
• count()
• del
• index
Concatenation :
• Join two or more tuples only.
• + operator is used to concatenate the tuples
Syntax : tuple1 + tuple2
Replication :
• It replicates tuple elements
• * operator is used to Replicate the tuples
Syntax : tuple * integer_Literal
Note : tup still remains unchanged
max() and min():
• max() function returns the maximum value
• min() function returns the minimum value
Syntax :
• max(tuple_name)
• min(tuple_name)
index() : The method returns the index value of an item. If item not found then error
is generated
syntax :
tuple_name.index(value)
Note : Here index value of 9 is obtained as it is in the tuple, but for 8 value error is
raised as it is not in the tuple.
del :
used to delete tuple. As tuples are immutable objects one cannot delete individual
elements.
Syntax :
del tuple_name
Note : If you try to use the tuple after using del, NameError will be generated
Note :
del tuple_name[index] #deleting an element at a particular index
or
del tuple_name[start : stop] #deleting a range of elements in tuple
will generate an error as individual or range of elements cannot be deleted in tuples.
count() : It is used to count the occurrence of an element in a tuple
Syntax :
tuple_name.count(value)