Lect 03 Tuple
Lect 03 Tuple
○ Indexing
○ Negative Indexing
● Update a Tuples
T1=(10,20,30,40)
T2=(“Ahaan”, 10,20,”Vihaan”)
print(T1)
print(T2) 3
Prof. Harish D. Gadade, COEP Technological University, Pune
Accessing Tuple Elements
● You can access tuple items by referring to the index number, inside
square brackets:
T=(“Ahaan”, 10,20,”Vihaan”)
print(T[0])
print(T[2])
print(T[3])
print(T[-1])
● Above example shows indexing with negative indexing
4
Prof. Harish D. Gadade, COEP Technological University, Pune
Tuple Slicing
● You can specify a range of indexes by specifying where to start and
where to end the range.
● When specifying a range, the return value will be a new tuple with the
specified items.
T=(“Ahaan”, 10,20,”Vihaan”)
print(T[:])
print(T[:4])
print(T[2:])
print)T[1:3])
print(T[:-1])
print(T[-3:-1])
5
Prof. Harish D. Gadade, COEP Technological University, Pune
Adding Element to Tuple
● Since tuples are immutable, they do not have a build-in append()
method, but there are other ways to add items to a tuple
○ Convert into a list: We can convert tuple into a list, add
item(s), and convert it back into a tuple.
○ Add tuple to a tuple: We can add tuples to tuples, so we you want
to add one item, (or many), create a new tuple with the item(s),
and add it to the existing tuple:
x = ("Ahaan",10,20,"Vihaan") x = ("Ahaan",10,20,"Vihaan")
y = list(x) y = (“Ayaan”)
y.append("Ayaan") x=x+y
x = tuple(y) print(x)
6
Prof. Harish D. Gadade, COEP Technological University, Pune
Deleting Element from Tuple
● Tuples are unchangeable, so you cannot remove items from it, but you
can use previous method for changing and adding tuple items:
○ Convert into a list: We can convert tuple into a list, add
item(s), and convert it back into a tuple.
x = ("Ahaan",10,20,"Vihaan")
y = list(x)
y.remove(“Vihaan”)
x = tuple(y)
7
Prof. Harish D. Gadade, COEP Technological University, Pune
Inbuilt Functions for Tuple
● Python provides various inbuilt functions that can be used with tuples