3. TUPLES
● Tuples are used to store multiple items in a single variable.
● It is a sequence of values separated by comma and enclosed within brackets.
● A tuple is a collection which is ordered and unchangeable.
● Tuple items are ordered, unchangeable and allow duplicate values.
EXAMPLE
Fruit = (‘apple’ , ‘banana’, ‘cherries’)
print(Fruit)
print(type(Fruit)
OUTPUT
(‘apple’ , ‘banana’, ‘cherries’)
<class ‘tuple’>
4. IMMUTABLE
CHANGE TUPLE VALUES, ADD ITEMS,
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x) // OUTPUT:(“kiwi”,”banana”,”cherry”)
ADD TUPLE TO TUPLE
● Allowed to add tuple to tuple by creating new tuple
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple) //OUTPUT: (‘apple’,’banana’,’cheery’,’orange’)
5. DELETING TUPLE ELEMENT
● Removing individual tuple element is not possible.
● Using del we can delete entire tuple
EXAMPLE
Fruit = ("apple", "banana", "cherry")
del Fruit
print(Fruit) #this will raise an error because the tuple no longer exists
6. BASIC TUPLE OPERATION
Some of the operation performed in tuples are:
Operation Example Output
Length Fruit = ("apple", "banana", "cherry")
print(len(Fruit))
3
Concatenation / join tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
('a', 'b', 'c', 1, 2, 3)
Repetition /
multiplying
fruits = ("apple", "banana", cherry")
Fruit = fruits * 2
print(Fruit)
('apple', 'banana', 'cherry', 'apple',
'banana', 'cherry')
Membership 3 in (1,2,3) True
Iteration 1.for x in (1,2,3):
Print x
2. fruits = ("apple", "banana", cherry")
for i in range(len(Fruit)):
print(Fruit[i])
1 2 3
apple
banana
cherry
7. TUPLE METHOD
1. count() - Returns the number of times a specified value occur in a tuple
2. index() - Searches the tuple for a specified value and returns the position of where it
was found
3. max() - Returns item from the tuple with max value
4. min() - Returns item from th etuple with min value
5. tuple(seq) - Converts to tuple
8. Tuple Indexing and Tuple Slicing
● Forward indexing
● Reverse indexing
Slicing Syntax:
Tuple_name[start index : stop index : step index]
9. TUPLE ASSIGNMENT
● Multiple assignment can be done
● Number of objects on left hand side should be equal to number of objects on the right
side
EXAMPLE:
>>X,Y =1,2,3
Value Error: Too many values to unpack
10. TUPLE AS RETURN VALUES:
EXAMPLE:
def circleinfo(r)
c = 2*3,14*r
a = 3.14*r*r
return (c,a)
r = int(input(“Enter the radius:”))
print(circleinfo(r))
OUTPUT
Enter the radius: 10
(62.8318, 314.159)
14. 4. for index, element in enumerate(‘abc):
print(index, element)
OUTPUT
0 a
1 b
2 c
15. DICTIONARIES AND TUPLE
1. d = {'a':0,'b':1,'c':2}
t = d.items()
print(t)
OUTPUT
dict_items([('a', 0), ('b', 1), ('c', 2)])
2. for key, value in d.items():
print(key, value)
OUTPUT
a 0
b 1
c 2