Tuples
• Introduction
• Creating and Accessing tuples
• Tuples operations
• Tuple Functions and Methods
Tuples- Tuples are immutable sequences of python. We cannot change the elements of a tuple in place.
It is a sequence of immutable objects. It is just like list. Difference between the tuples and the lists is that the tuples
cannot be changed unlike lists. Lists uses square bracket whereas tuples use parentheses.
Creating and Accessing tuples
Creating A Tuple
A tuple is enclosed in parentheses () for creation and each item is separated by a comma.
e.g.
tup1 = (‘comp sc', ‘info practices', 2017, 2018)
tup2 = (5,11,22,44)
NOTE:- Indexing of tuple is just similar to indexing of list.
Tuples operations
• Joining – joining two tuples
tp1=(1,3,5)
tp2=(6,7,8)
tp1+tp2 (1,3,5,6,7,8)
• Slicing the tuples – tuple slices like list and string slice are the sub part of the tuple extracted out.
tp1=(10,12,14,20,22,24,30,32,34)
Seq=tp1[3:-3]
(20,22,24)
• Comparing- Compare two tuples <,>,==, !=
Example-
a=(2,3)
b=(2,3)
a==b
True
• Unpacking- creating a tuple from a set of values is called packing and its reverse. Creating individual values
form tuple elements is called unpacking
Syntax-
<var1>, <var2>, <var3>….=t
Example-
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
output-
apple
banana
cherry
• Deleting - The del keyword can delete the tuple completely
fruit = ("apple", "banana", "cherry")
fruit
print(fruit)
#this will raise an error because the tuple no longer exists after delete this tuple after access it make error.
Tuples function and methods-
1. len()- return the length of a tuple.
Synatx- len(tuple)
employee=(“john”, 10000,24, “sales”)
len(employee)
4
2. max()- return the maximum value of tuple.
Tp1= (“Karan’, “Zubin”, “Zara”, “Ana”)
Max(tp1)
Zubin
3. min() and sum()-
Example –
tp1= (10,12,14,20,22,24,30,32,34)
min(tp1)=10
sum(tp1)=126
4. index()- The index () work with tuples same in list
Example- t1=(3,4,5,6.2)
[Link](5)
2
Example –
vowels = ('a', 'e', 'i', 'o', 'i', 'u')
index = [Link]('e')
print('The index of e:', index)
OUTPUT ->1
5. Sorted()-sorted()- returns the sorted elements list
x = (1,4,6)
r= sorted(x)
print(sorted elements in tuple', r)
6. count() - method returns the number of times a specified value appears in the tuple.
t1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
OUTPUT-> 5