10 Notes Tuples
10 Notes Tuples
A tuple can have different types of data items like integers, floating
point numbers etc.
tup1 = (‘comp sc', ‘info practices', 2017, 2018)
Strings and Tuples are immutable. Lists and Dictionary are mutable.
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)
() empty tuple
print(my_tuple)
Lets see through Program example how List is changeable and Tuple isn’t
picnic= ["ColdDrinks","Juices","Chocolates","Crisps","Nachos"]
picnic[3]= "Chips"
tpicnic= ("ColdDrinks","Juices","Chocolates","Crisps","Nachos")
print(picnic)
0 1 2 3 4 5 6 7 8
a b c d e f g h i
-9 -8 -7 -6 -5 -4 -3 -2 -1
Lets take Tuple T = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') and see how Tuple slicing works
Inputting a tuple
1. If we wish to enter elements through keyboard:
x= input("Enter elements of tuple ")
print(x)
Output:
Enter elements of tuple Responsibility
Responsibility (This is a String)
('R', 'e', 's', 'p', 'o', 'n', 's', 'i', 'b', 'i', 'l', 'i', 't', 'y') (This is a tuple now)
1. The len() method – It returns length of the tuple, i.e. ,the count of elements
in the tuple.Ex:
>>>tp=(1,2,3)
>>>len(tp)
Output:
3
2. The max() method – It returns the element from the tuple having
maximum value.Ex:
>>>tp=(10,5,78)
>>>max(tp)
Output:
78
3. The min() method – It returns the element from the tuple having minimum
value. Ex:
>>>tp =(9,3,1)
>>>min(tp)
Output:
1
4. The index() method – It returns the index of an existing element of a tuple
(Starting index is 0) .Ex:
>>>t1=(3,4,5,6)
>>>t1.index(5)
Output:
2
5. The count() function – This method returns the count of a member
element in a given tuple. Ex:
>>>t1=(2,3,4,5,6,2,7,8,2)
>>>t1.count(2)
Output:
3
6. The tuple() method – It can be used to create tuples from different types of
values.
>>>t= tuple(“abc”)
>>>t
Output:
(‘a’, ‘b’, ‘c’) (See that output is a tuple, so it is enclosed in ( )-elements separated by commas )
7. The sorted() method- It is used to sort a tuple. Passing a tuple to sorted() returns a
sorted list.
t1 = (3, 1, 4, 5, 2)
x = sorted(t1)
print(t1)
print(x)
Output:
(3, 1, 4, 5, 2)
[1, 2, 3, 4, 5] see that the sorted method/function sorts the tuple and returns it as a list.
t=(3,5,7,2,5)
print(t)
notimes= t.count(x)
if notimes ==0:
Output:
(3, 5, 7, 2, 5)
Linear Search in a Tuple. (Search for an element in a Tuple without using count()
WAP to let the user enter an element. Search and display how many times it is
present in the tuple
t=(3,5,7,2,5)
print(t)
c=0
L=len(t)
for i in range(0,L):
if(t[i]==x):
c=c+1
if (c==0):
else:
Output:
(3, 5, 7, 2, 5)
Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is, in fact, a tuple.
mytuple = (9)
mytuple = (9,)
mytuple = 9,
print(type(mytuple)) # displays <class 'tuple'>
Program
If we enter tuple with one element with input() and print the tuple, it displays the element with a
,(comma)
x= input("Enter elements of tuple ")
print(x)
t=tuple(x) # making string as tuple by using tuple function
print("The Tuple is: ")
print(t)
Output:
Enter elements of tuple 1
1
The Tuple is:
('1',)
Lpicnic= list(picnic)
Lpicnic[3]="Chips"
print(Lpicnic)
picnic=tuple(Lpicnic)
print(picnic)
Program
Input elements of a Tuple (numbers) through keyboard. (We let the user enter
through keyboard, append them in a List. Then make that list into a Tuple)
L=[]
for i in range(0,5):
x=int(input("Enter a number "))
L.append(x)
tuple1=tuple(L)
print(tuple1)
Output:
Enter a number 23
Enter a number 34
Enter a number 45
Enter a number 6
Enter a number 2
(23, 34, 45, 6, 2)
Tuple Operations :
Ex 1 :
>>>t=(‘p’,‘u’,‘r’,‘e’)
>>>for i in t:
print(t[i])
p
u
r
e
Ex 2: WAP to let the user enter a few integers in a tuple. Traverse the
tuple and display each element of tuple.
x= input("Enter elements of tuple ")
print(x)
for a in t:
print(a)
Output:
2. Joining Tuple – The + operator, when used with two tuples, joins two
tuples.Ex:
>>>t1=(1,2,3)
>>>t2=(4,5)
>>>t1 + t2
(1,2,3,4,5)
# Concatenation
# Output: (1, 2, 3, 4, 5, 6)
print((1, 2, 3) + (4, 5, 6))
# Repeat
# Output: ('Repeat', 'Repeat', 'Repeat')
print(("Repeat",) * 3)
Membership operator:
Working of membership operator “in” and “not in” is same as in a list
We can test if an item exists in a tuple or not, using the keyword in .
# In operation
print('a' in my_tuple) # will display True
print('b' in my_tuple) # will display False
# Not in operation
print('g' not in my_tuple) #will display True
Updating Tuples
Tuples are immutable,that’s why we can’t change the content of tuple.It’s alternate
way is to take contents of existing tuple and create another tuple with these contents
as well as new content.
E.g.
tup1 = (1, 2)
tup2 = ('a', 'b')
tup3 = tup1 + tup2
print (tup3)
Output :
(1,2,’a’,’b’)
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Direct deletion of tuple element is not possible but shifting of required content after discard
of unwanted content to another tuple.
e.g.
tup1 = (1, 2,3)
tup3 = tup1[0:1] + tup1[2:]
print (tup3)
Output:
(1,3)
Adding element in tuple though tuple is immutable
Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not
allowed. However, following workaround can be used.
Then use another built-in function tuple() to convert this list object back to tuple.You can see new
element appended to original tuple representation.
>>> T1=(10,50,20,9,40,25,60,30,1,56)
>>> L1=list(T1)
>>> L1
>>> L1.append(100)
>>> T1=tuple(L1)
>>> T1
Nested Tuples
Accessing elements from nested tuples
(10, 50, 20, 9, 40, 25, 60, 30, 1, 56, 100)
Double indexes are used to access the elements of nested tuple. The first index represents the element of main
tuple and the second index represent the element of the nested tuple.
my_data is a tuple.
In the following example, when I used my_data[2][1], it accessed the second element of the nested tuple.
Because 2 represented the third element of main tuple which is a tuple and the 1 represented the second
element of that tuple.
# prints 'v'
print(my_data[1][3])
# prints 22
print(my_data[2][1])
Output:
v
22
Questions
Ans: Immutable types are those data types that can never change their value . In Python the following
types are immutable:
(i) integers
(ii) floating-point numbers
(iii) Booleans
(iv) Strings
(v) Tuples
4. If a is (1, 2, 3), what is the difference (if any) between a*3
and [a, a, a]?
Ans: a*3 is different from [a,a,a] because, a*3 will produce a tuple (1,2,3,1,2,3,1,2,3) and
[a, a, a] will produce a list of tuples [(1,2,3),(1,2,3),(1,2,3)].
5. If a is (1, 2, 3), is a *3 equivalent to a + a + a?
Ans: Yes both give (1,2,3,1,2,3,1,2,3)
6. If a is (1, 2, 3), what is the meaning of a [1:2] = 4 and a [1:1]
= 4?
Ans: This will produce an error: TypeError: 'tuple' object does
not support item assignment
7. Does a slice operator always produce a new Tuple?
Ans: Yes
8. How is an empty Tuple created?
Ans: To create an empty tuple we have to write –
>>>T=() or >>>T=tuple()
9. How is a tuple containing just one element created?
Ans: Following methods may be used to create single valued
tuple –
>>>T=3, or >>>T=(4,)
10. What is (30,)?
SN List Tuple
1 List elements are enclosed in []. Tuple elements are enclosed in ().
3 The List has the a variable length because we can add The tuple has the fixed length.
or remove elements.
4 The list is used in the scenario in which we need to The tuple is used in the cases where
store the simple collections with no constraints where we need to store the read-only
the value of the items can be changed. collections i.e., the value of the
items cannot be changed. It can be
used as the key inside the
dictionary.
Ans: Convert tuple into list and add or We can add an extra element to the tuple as follows –
a=0
b=1 a=1
c=1 b=1
c= 2
Q.2 WAP that creates a third tuple after adding two tuples. Add second after first tuple.
Ans:
Q.3 WAP to calculate the mean of the numbers of the
tuple. Ans:
x=eval(input("Enter elements of tuple"))
y=tuple(x) #(1,2,3)
print(y)
L=len(y) # in example it will be 3
sum=0
for i in range(0,L):
sum=sum+y[i]
av=sum/L
print(av)
Answers:
(i) fruit=('banana','mango','apple','peach','grapes')
(ii) City=('Delhi','Chennai','Kannur','Jalandhar','Hyderabad')
(iii) Mixed=('banana','apple','grapes',12,13)
(iv) Box=(1,5,2,['a','b'])
(v) R10=(random.randint(10,50) for i in range(10))
(vi) F10=(random.randint(1000,4999)/100 for i in range(10))
(vii) y=(x*x+2*x-1 for x in range(-4,6))
(viii) C=(random.randint(-30,-20)
for x in range(10))
(ix) A=[3,5,6.7]
B=(A,1,2,3)
(x) A=(3,5,6.7)
B=(A,(1,2,3))
.
(i) True (ii) False (iii) False (iv) True
(v) True (vi) False (vii) False (viii)
True
(ix) True (x) False
Output:
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)
Programs
2. Create a tuple with 9 elements. Let the user enter a number. Display
how many times it is present.
tuple1 = (2, 4, 5, 6, 2, 3, 4, 4, 7 )
n=int(input("Enter number to be searched "))
print(tuple1)
#return the number of times it appears in the tuple.
count = tuple1.count(n)
print(count)
Output if 4 is input
(2, 4, 5, 6, 2, 3, 4, 4, 7 )
3
3. Modify the above program. Let the user enter 5 elements. Let the user
enter a number to be searched. Display how many times it is present in
the tuple.
L=[]
for i in range(0,5):
x=int(input("Enter a number "))
L.append(x)
tuple1=tuple(L)
print(tuple1)
Output:
Enter a number 3
Enter a number 5
Enter a number 7
Enter a number 2
Enter a number 3
Enter number to be searched 3
(3, 5, 7, 2, 3)
No of times Present 2
(Modify the program to display whether searched number is present or not.. Tip : if count1==0 )
Output:
('w', 3, 'r', 'c', 'e')
('w', 3, 'c', 'e')
n=x-1
Output:
6. Create 2 tuples with characters and integers. Reverse them and display reversed
tuples.
#create a tuple
x = ("m", "a")
# Reversed the tuple
y = reversed(x)
print(tuple(y))