Professional Documents
Culture Documents
Tuple
Tuple
ADVANCE PYTHON
TUPLE
• Tuple is a collection of elements which is ordered
and unchangeable (Immutable). Immutable
means you cannot change elements of a tuple in
place.
• Consists the values of any type, separated by
Tuple comma.
• Allows duplicate members.
• Tuples are enclosed within parentheses ( ).
• Cannot remove the element from a tuple.
• Eg:
T1=(45,23,33.5,'hello',40,'world')
print(T1)
ACCESSING TUPLES
• Tuples are very much similar to lists.
• Tuple elements are also indexed.
• Forward indexing as 0,1,2,3,4………
• backward indexing as -1,-2,-3,-4,………
• The values stored in a tuple can be accessed using the slice operator ([:]) with
indexes.
Eg: Tuple_name[start:end] will give you elements between start to end-1.
• The first item in the tuple has the index zero (0).
Example:
>>> text=(‘c’,’o’,’m’,’p’,’u’,’t’,’e’,’r’)
TUPLE METHODS
Function name Description
• The del statement is used to delete elements and objects but as you
know that tuples are immutable, which also means that individual
element of a tuple cannot be deleted.
T=(2,4,6,8,10,12,14)
del(t[3]) #error as tuple is immutable
Examples
#create tuple
T1=(45,23,33.5,'hello',40,'world')
print(T1)
#Accessing values
text=(2,4,8,9,3,'abc',12)
print("Value",text[4])
print("Value",text[2:5])
print("Value",text[-3])
print("Value",text[-5:-1])
#Operations
t1=(4,6,9,2)
t2=(2,3,6,7)
print(t1+t2)
print(t1*3)
s=0
for i in text:
s=s+i
print("Sum:",s)
print("Average=",s/len(text))
# Write a program to create two tuples with different values and
combine both the tuple and make a new tuple.
t1=(34,25,46,65)
t2=(12,16,35,56)
t3= t1+t2
print(t3)
PRACTICE QUESTIONS ON TUPLE
1. Create a tuple with given values
Tup = (10, 20, 30, 40, 50)
• Access value 20 from the above tuple
• Access value from 1st index to 4th index from Tup.
2. Count the number of occurrences of item 50 in tuple1
tuple1 = (50, 10, 60, 70, 50)
3. Write a python program to create a tuple with different values and count the number of items in the tuple.
4. Write a program to create a tuple ‘Marks’ with the marks of a student in five subjects. Print the maximum and
minimum marks.
5. WAP to create a tuple with values t1= (102, 230, 385, 438, 505).