Tupple
Tupple
Q1. Why tuples are called immutable types?
Ans. Tuples are called immutable types because we cannot
change elements of a tuple in place.
Q2. What are mutable counterparts of tuple?
Ans. Lists are mutable counterparts of tuple.
Q3. What are different ways of creating a tuple?
Ans. Tuples can be created by the following ways:
·
By placing a sequence of values separated by
comma within parentheses.
Example: tup = (1, 2, 3)
·
By placing a sequence of values separated by
comma without parentheses (parentheses are optional).
Example: tup = 1, 2, 3
·
By using the built-in tuple type object (tuple(
)) to create tuples from sequences as per the syntax given below: T =
tuple(<sequence>)
·
Where sequence can be any type of sequence
object like strings, tuples, lists, etc.
Example: tup = tuple([1, 2, 3,
4])
Q4. What values can we have in a tuple? Do they all have
to be the same type*?
Ans. No, all the elements of the tuple need not be of the
same type. A tuple can contain elements of all data types.
Q5. How are individual elements of tuples accessed?
Ans. The individual elements of a tuple are accessed
through their indexes given in square brackets as shown in the example below:
Example:
tup = ("python",
"tuple", "computer")
print(tup[1])
Output
tuple
Q6. How do you create the following tuples?
(a) (4, 5, 6)
(b) (-2, 1, 3)
(c) (-9, -8, -7, -6, -5)
(d) (-9, -10, -11, -12)
(e) (0, 1, 2)
Ans.
(a) tup = (4, 5, 6)
(b) tup = (-2, 1, 3)
(c) tup = (-9, -8, -7, -6, -5)
(d) tup = (-9, -10, -11, -12)
(e) tup = (0, 1, 2)
Q7. If a = (5, 4, 3, 2, 1, 0) evaluate the following
expressions:
(a) a[0]
(b) a[1]
(c) a[a[0]]
(d) a[a[-1]]
(e) a[a[a[a[2]+1]]]
Ans. (a) 5 (b) 4
(c) 0 (d) 5 (e) 1
Q 8. Can you change an element of a sequence? What if a
sequence is a dictionary? What if a sequence is a tuple?
Ans. Yes, we can change any element of a sequence in
python only if the type of the sequence is mutable.
Dictionary — We can change the
elements of a dictionary as dictionary is a mutable sequence. For example:
d = {'k1':1, 'k2':4}
d['k1'] = 2
Tuple — We cannot change the elements of a tuple as tuple
is an immutable sequence. For example:
tup = (1, 2, 3, 4)
tup[0] = 5
The above expression will give
an error.
TypeError: 'tuple' object does
not support item assignment
Q9. What does a + b amount to; if a and b are tuples?
Ans. Given a and b are tuples, so in this case the +
operator will work as concatenation operator and join both the tuples.
For example:
a = (1, 2, 3)
b = (4, 5, 6)
c = a + b Here,
c is a tuple with elements (1, 2, 3, 4, 5, 6)
Q10. What does a * b amount to; if a and b are tuples?
Ans. If a and b are tuples then a * b will throw an error
since a tuple can not be multiplied to another tuple.
TypeError: can't multiply
sequence by non-int of type 'tuple'
Q 11. What does a
+ b amount to if a is a tuple and b is 5?
Ans. If a is tuple and b is 5 then a + b will raise a
TypeError because it is not possible to concatenate a tuple with an integer.
For example:
a = (1, 2)
b = 5
c = a + b
Output
TypeError: can only concatenate
tuple (not "int") to tuple
Q12. Is a string the same as a tuple of characters?
Ans. No, a string and a tuple of characters are not the
same even though they share similar properties like immutability,
concatenation, replication, etc.
A few differences between them are as follows:
1. in operator works differently in both of them. Below
example shows this difference. Example:
my_string = "Hello"
my_tuple = ('h','e','l','l','o')
print("el" in my_string)
print("el" in my_tuple)
Output
True
False
2. Certain functions like split( ), capitalize( ), title(
), strip( ), etc. are present only in string and not available in tuple object.
Q13. Can you have an integer, a string, a tuple of
integers and a tuple of strings in a tuple?
Ans. Yes, it is possible to have an integer, a string, a
tuple of integers and a tuple of strings in a tuple because tuples can store
elements of all data types.
For example:
tup = (1, 'python', (2, 3), ('a', 'b'))
Multiple Choice Qs
Q1. Which of the following statements will create a
tuple:
(a)
tp1=("a",
"b")
(b)
tp1[2]=("a", "b")
(c)
tp1=(3)*3
(d)
None of these
Q2. Choose the correct statement(s).
(a)
Both tuples and lists are immutable.
(b)
Tuples are immutable
while lists are mutable.
(c)
Both tuples and lists are mutable.
(d)
Tuples are mutable while lists are immutable.
Q3. Choose the correct statement(s).
(a)
In Python, a tuple can contain only integers as
its elements.
(b)
In Python, a tuple can contain only strings as
its elements.
(c)
In Python, a tuple can contain
elements of different types.
(d)
In Python, a tuple can contain either string or
integer but not both at a time
Q4. Which of the following is/are correctly declared
tuple(s)?
(a)
a = ("Hina",
"Mina", "Tina", "Nina")
(b)
a = "Hina", "Mina",
"Tina", "Nina")
(c)
a = ["Hina", "Mina",
"Tina", "Nina"]
(d)
a = (["Hina", "Mina",
"Tina", "Nina"])
Q5. Which of the
following will create a single element tuple?
(a)
(1,) (b) (1) (c) ( [1] ) (d) tuple([1])
Q6. What will be the output of following Python code?
tp1 = (2,4,3)
tp3 = tp1*2
print(tp3)
(a) (4,8,6)
(b) (2,4,3,2,4,3)
(c) (2,2,4,4,3,3)
(d) Error
Ans. (2,4,3,2,4,3)
Q7. What will be the output of following Python code?
tp1 = (15,11,17,16,12)
tp1.pop(12)
(a)
print(tp1)
(b)
(15,11,16,12)
(c)
(15,11,17,16)
(d)
(15,11,17,16,12)
(e)
Error Reason — As tuples are immutable so
they don't support pop operation.
Q8. Which of the following options will not result in an
error when performed on types in Python where tp = (5,2,7,0,3) ?
tp[1] = 2
tp.append(2)
tp1=tp+tp
tp.sum()
Q9. What will be the output of the following Python code?
tp = ()
tp1 = tp * 2
print(len(tp1))
(a) 0
(b) 2
(c) 1
(d) Error
Q10. What will be the output of the following Python
code?
tp = (5)
tp1 = tp * 2
print(len(tp1))
(a) 0
(b) 2
(c) 1
(d) Error Reason —
tp is not a tuple and holds an integer value hence object of type 'int' has no
len()
Q11. What will be the output of the following Python
code?
tp = (5,)
tp1 = tp * 2
print(len(tp1))
(a) 0
(b) 2
(c) 1
(d) Error
Q12.
Given tp = (5,3,1,9,0). Which of the following two
statements will give the same output?
(i) print( tp[:-1] )
(ii) print( tp[0:5] )
(iii) print( tp[0:4] )
(iv) print( tp[-4:] )
(a)
(i), (ii)
(b)
(ii), (iv)
(c)
(i), (iv)
(d)
(i), (iii)
Q13. What is the output of the following code?
t = (10, 20, 30, 40, 50, 50,
70)
print(t[5:-1])
(a) Blank
output( )
(b) (50,70)
(c) (50,50,70)
(d) (50,)
Q14. What is the output of the following code?
t = (10, 20, 30, 40, 50, 60,
70)
print(t[5:-1])
(a) (60,)
(b) (10,
20, 30, 40, 50)
(c) (10,
30, 50, 70)
(d) (10,
20, 30, 40, 50, 60, 70)
Q15. Which of the below given functions cannot be used
with nested tuples ?
(a)
index( )
(b)
count( )
(c)
max( )
(d)
sum( )
Fill in the Blanks
Q1. Tuples are immutable data types of Python.
Q2. A tuple can store values of all data types.
Q3. The + operator used with two tuples, gives a
concatenated tuple.
Q4. The * operator used with a tuple and an integer,
gives a replicated tuple.
Q5. To create a single element tuple storing element 5,
you may write t = ( 5, ).
Q6. The in operator can be used to check for an element's
presence in a tuple.
Q7. The len( ) function returns the number of elements in
a tuple.
Q8. The index( ) function returns the index of an element
in a tuple.
Q9. The sorted( ) function sorts the elements of a tuple
and returns a list.
Q10. The sum( ) function cannot work with nested tuples.
State True or False
Q1. Tuples in Python are mutable. False
Q2. The elements in a tuple can be deleted. False
Q3. A Tuple can store elements of different types. True
Q4. A tuple cannot store other tuples in it. False
Q5. A tuple storing other tuples in it is called a nested
tuple. True
Q6. A tuple element inside another element is considered
a single element. True
Q7. A tuple cannot have negative indexing. False
Q8. With tuple( ), the argument passed must be sequence
type. True
Q9.All tuple functions work identically with nested
tuples. False
Q10.Functions max( ) and min( ) work with all types of
nested tuples. False
Type A : Short Ans. Qs/Conceptual.
Q1. Discuss the utility and significance of tuples,
briefly.
Ans. Tuples are used to store multiple items in a single
variable. It is a collection which is ordered and immutable i.e., the elements
of the tuple can't be changed in place. Tuples are useful when values to be
stored are constant and need to be accessed quickly.
Q2. If a is (1, 2, 3):
(a)
What is the difference (if any) between a * 3
and (a, a, a)?
(b)
Is a * 3 equivalent to a + a + a?
(c)
What is the meaning of a[1:1] ?
(d)
What is the difference between a[1:2] and a[1:1]
?
Ans.
(a)
a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒
((1, 2, 3), (1, 2, 3), (1, 2, 3))
So, a * 3 repeats the elements
of the tuple whereas (a, a, a) creates nested tuple.
(b)
Yes, both a * 3 and a + a + a will result in (1,
2, 3, 1, 2, 3, 1, 2, 3).
(c)
This colon indicates (:) simple slicing
operator. Tuple slicing is basically used to obtain a range of items. tuple[Start
: Stop] ⇒ returns the portion of the tuple from index Start to
index Stop (excluding element at stop).
a[1:1] ⇒ This will
return empty list as a slice from index 1 to index 0 is an invalid range.
(d)
Both are creating tuple slice with elements
falling between indexes start and stop.
a[1:2] ⇒ (2,)
It will return elements from
index 1 to index 2 (excluding element at 2).
a[1:1] ⇒ ()
a[1:1] specifies an invalid
range as start and stop indexes are the same. Hence, it will return an empty
list.
Q3. Does the slice operator always produce a new tuple?
Ans. No, the slice operator does not always produce a new
tuple. If the slice operator is applied on a tuple and the result is the same
tuple, then it will not produce a new tuple, it will return the same tuple as
shown in the example below:
a = (1, 2, 3)
print(a[:])
Slicing tuple a using a[:] results in the same tuple.
Hence, in this case, slice operator will not create a new tuple. Instead, it
will return the original tuple a.
Q4. The syntax for a tuple with a single item is simply
the element enclosed in a pair of matching parentheses as shown below:
t = ("a")
Is the above statement true? Why? Why not?
Ans. The statement is false. Single item tuple is always
represented by adding a comma after the item. If it is not added then python
will consider it as a string.
For example:
t1 = ("a",)
print(type(t1)) ⇒ tuple
t = ("a")
print(type(t)) ⇒ string
Q5. Are the following two assignments same? Why / why not?
1.
T1 = 3, 4,
5
T2 = ( 3, 4 , 5)
T3 = (3, 4,
5)
T4 = (( 3, 4,
5))
Ans. T1 and T2 are same. Both are tuples. We can
exclude/include the parentheses when creating a tuple with multiple values.
T3 and T4 are not same. T3 is a tuple whereas T4 is a
nested tuple.
Q6. What would following statements print? Given that we
have tuple= ('t', 'p', 'l')
print("tuple")
print(tuple("tuple"))
print(tuple)
Ans.
print("tuple") ⇒ tuple
It will simply print the item inside the print statement
as it is of string type.
print(tuple("tuple")) ⇒ it will
throw error.
TypeError: 'tuple' object is not callable
This is because the variable "tuple" is being
used to define a tuple, and then is being used again as if it were a function.
This causes python to throw the error as now we are using tuple object as a
function but it is already defined as a tuple.
print(tuple) ⇒ ('t', 'p', 'l')
It will return the actual value of tuple.
Q7. How is an empty tuple created?
Ans. There are two ways of creating an empty tuple:
·
By giving no elements in parentheses in
assignment statement.
Example:
emptyTuple = ()
·
By using the tuple function.
Example:
emptyTuple = tuple()
Q8. How is a tuple containing just one element created?
Ans. There are two ways of creating single element tuple:
By enclosing the element in parentheses and adding a
comma after it.
Example: t = (a,)
By using the built-in tuple type object (tuple( )) to
create tuples from sequences:
Example:
t = tuple([1])
Here, we pass a single element list to the tuple function
and get back a single element tuple.
Q9. How can you add an extra element to a tuple?
Ans. We can use the concatenation operator to add an
extra element to a tuple as shown below. As tuples are immutable so they cannot
be modified in place.
For example:
t=(1,2,3)
t_append = t + (4,)
print(t)
print(t_append)
Output:
(1,2,3)
(1,2,3,4)
Q10. When would you prefer tuples over lists?
Ans. Tuples are preferred over lists in the following
cases:
When we want to ensure that data is not changed
accidentally. Tuples being immutable do not allow any changes in its data.
When we want faster access to data that will not change
as tuples are faster than lists.
When we want to use the data as a key in a dictionary.
Tuples can be used as keys in a dictionary, but lists cannot.
When we want to use the data as an element of a set.
Tuples can be used as elements of a set, but lists cannot.
11. What is the difference between (30) and (30,)?
Ans.
a = (30) ⇒ It will be treated as an integer
expression, hence a stores an integer 30, not a tuple.
a = (30,) ⇒ It is considered as single
element tuple since a comma is added after the element to convert it into a
tuple.
Q12. When would sum( ) not work for tuples
Ans. Sum would not work for the following cases:
When tuple does not have numeric value.
For example:-
tup = ("a", "b")
tup_sum = sum(tup)
TypeError: unsupported operand type(s) for +: 'int' and
'str'
here, "a" and "b" are string not
integers therefore they can not be added together.
Nested tuples having tuple as element.
For example:-
a = (1,2,(3,4))
print(sum(a))
Output:
TypeError: unsupported operand type(s) for +: 'int' and
'tuple'
Here, tuple 'a' is a nested tuple and since it consist of
another tuple i.e. (3,4) it's elements can not be added to another tuple. Hence
it will throw an error.
Tuple containing elements of different data type.
For example:-
a = (1,2.5,(3,4),"hello")
print(sum(a))
Output:
TypeError: unsupported operand type(s) for +: 'float' and
'tuple'
Tuple a contains elements of integer, float, string and
tuple type which can not be added together.
Q13. Do min( ), max( ) always work for tuples ?
Ans. No, min( ), max( ) does not always work for tuples.
For min( ), max( ) to work, the elements of the tuple should be of the same
type.
Q14. Is the working of in operator and tuple.index( )
same ?
Ans. Both in operator and tuple.index( ) can be used to
search for an element in the tuple but their working it is not exactly the
same.
The "in" operator returns true or false whereas
tuple.index() searches for a element for the first occurrence and returns its
position. If the element is not found in tuple or the index function is called
without passing any element as a parameter then tuple.index( ) raises an error:
For Example:-
tuple = (1, 3, 5, 7, 9)
print(3 in tuple) ⇒ True
print(4 in tuple) ⇒ False
print(tuple.index(3)) ⇒ 1
print(tuple.index(2)) ⇒ Error
ValueError: tuple.index(x): x not in tuple
print(tuple.index()) ⇒ Error
TypeError: index expected at least 1 argument, got 0
Q15. How are in operator and index( ) similar or
different ?
Ans. Similarity: in operator and index( ) both search for
a value in tuple.
Difference: in
operator returns true if element exists in a tuple otherwise returns false.
While index( ) function returns the index of an existing element of the tuple.
If the given element does not exist in tuple, then index( ) function raises an
error.
Type B:
Application Based
Q 1(a) Find the output generated by following code fragments:
plane = ("Passengers",
"Luggage")
plane[1] = "Snakes"
Ans. Output
TypeError: 'tuple' object does not support item
assignment
Explanation
Since tuples are immutable, tuple object does not support
item assignment.
Q 1(b) Find the output generated by following code
fragments :
(a, b, c) = (1, 2, 3)
Ans.
Output
a = 1
b = 2
c = 3
Explanation
When we put tuples on both sides of an assignment
operator, a tuple unpacking operation takes place. The values on the right are
assigned to the variables on the left according to their relative position in
each tuple. As you can see in the above example, a will be 1, b will be 2, and
c will be 3.
Q 1(c) Find the output generated by following code
fragments :
(a, b, c, d) = (1, 2, 3)
Ans.
Output
ValueError: not enough values to unpack (expected 4, got
3)
Explanation
Tuple unpacking requires that the list of variables on
the left has the same number of elements as the length of the tuple. In this
case, the list of variables has one more element than the length of the tuple
so this statement results in an error.
Q 1(d) Find the output generated by following code
fragments :
a, b, c, d = (1, 2, 3)
Ans. Output
ValueError: not enough values to unpack (expected 4, got
3)
Explanation
Tuple unpacking requires that the list of variables on
the left has the same number of elements as the length of the tuple. In this
case, the list of variables has one more element than the length of the tuple
so this statement results in an error.
Q 1(e) Find the output generated by following code
fragments :
a, b, c, d, e = (p, q, r, s, t) = t1
Ans. Output
Assuming t1 contains (1, 2.0, 3, 4.0, 5), the output will
be:
a = 1
p = 1
b = 2.0
q = 2.0
c = 3
r = 3
d = 4.0
s = 4.0
e = 5
t = 5
Explanation
The statement unpacks the tuple t1 into the two variable
lists given on the left of t1. The list of variables may or may not be enclosed
in parenthesis. Both are valid syntax for tuple unpacking. t1 is unpacked into
each of the variable lists a, b, c, d, e and p, q, r, s, t. The corresponding
variables of the two lists will have the same value that is equal to the
corresponding element of the tuple.
Q 1(f) a, b, c, d, e = (p, q, r, s, t) = t1
What will be the values and types of variables a, b, c,
d, e, p, q, r, s, t if t1 contains (1, 2.0, 3, 4.0, 5) ?
Ans.
Variable Value Type
a 1 int
b 2.0 float
c 3 int
d 4.0 float
e 5 int
p 1 int
q 2.0 float
r 3 int
s 4.0 float
t 5 int
Explanation
The statement unpacks the tuple t1 into the two variable
lists given on the left of t1. The list of variables may or may not be enclosed
in parenthesis. Both are valid syntax for tuple unpacking. t1 is unpacked into
each of the variable lists a, b, c, d, e and p, q, r, s, t. The corresponding
variables of the two lists will have the same value that is equal to the
corresponding element of the tuple.
Q 1(g) Find the output generated by following code
fragments:
t2 = ('a')
type(t2)
Ans. Output
<class 'str'>
Explanation
The type() function is used to get the type of an object.
Here, 'a' is enclosed in parenthesis but comma is not added after it, hence it
is not a tuple and belong to string class.
Q 1(h) Find the output generated by following code
fragments :
t3 = ('a',)
type(t3)
Ans.
Output
<class 'tuple'>
Explanation
Since 'a' is enclosed in parenthesis and a comma is added
after it, so t3 becomes a single element tuple instead of a string.
Q 1(i)
Find the output generated by following code fragments :
T4 = (17)
type(T4)
Ans.
Output
<class 'int'>
Explanation
Since no comma is added after the element, so even though
it is enclosed in parenthesis still it will be treated as an integer, hence T4
stores an integer not a tuple.
Q 1(j)
Find the output generated by following code fragments :
T5 = (17,)
type(T5)
Ans.
Output
<class 'tuple'>
Explanation
Since 17 is enclosed in parenthesis and a comma is added
after it, so T5 becomes a single element tuple instead of an integer.
Q 1(k)
Find the output generated by following code fragments :
tuple = ( 'a' , 'b',
'c' , 'd' , 'e')
tuple = ( 'A', ) + tuple[1: ]
print(tuple)
Ans.
Output
('A', 'b', 'c', 'd', 'e')
Explanation
tuple[1:] creates a tuple slice of elements from index 1 (indexes
always start from zero) to the last element i.e. ('b', 'c', 'd', 'e').
+ operator concatenates tuple ( 'A', ) and tuple slice
tuple[1: ] to form a new tuple.
Q 1(l)
Find the output generated by following code fragments :
t2 = (4, 5, 6)
t3 = (6, 7)
t4 = t3 + t2
t5 = t2 + t3
print(t4)
print(t5)
Ans.
Output
(6, 7, 4, 5, 6)
(4, 5, 6, 6, 7)
Explanation
Concatenate operator concatenates the tuples in the same
order in which they occur to form new tuple. t2 and t3 are concatenated using +
operator to form tuples t4 and t5.
Q 1(m)
Find the output generated by following code fragments :
t3 = (6, 7)
t4 = t3 * 3
t5 = t3 * (3)
print(t4)
print(t5)
Ans.
Output
(6, 7, 6, 7, 6, 7)
(6, 7, 6, 7, 6, 7)
Explanation
The repetition operator * replicates the tuple specified
number of times. The statements t3 * 3 and t3 * (3) are equivalent as (3) is an
integer not a tuple because of lack of comma inside parenthesis. Both the
statements repeat t3 three times to form tuples t4 and t5.
Q 1(n)
Find the output generated by following code fragments :
t1 = (3,4)
t2 = ('3' , '4')
print(t1 + t2 )
Ans.
Output
(3, 4, '3', '4')
Explanation
Concatenate operator + combines the two tuples to form
new tuple.
Q 1(o)
What will be stored in variables a, b, c, d, e, f, g, h,
after following statements ?
perc = (88,85,80,88,83,86)
a = perc[2:2]
b = perc[2:]
c = perc[:2]
d = perc[:-2]
e = perc[-2:]
f = perc[2:-2]
g = perc[-2:2]
h = perc[:]
Ans.
The values of variables a, b, c, d, e, f, g, h after the
statements will be:
a ⇒ ( )
b ⇒ (80, 88, 83, 86)
c ⇒ (88, 85)
d ⇒ (88, 85, 80, 88)
e ⇒ (83, 86)
f ⇒ (80, 88)
g ⇒ ( )
h ⇒ (88, 85, 80, 88, 83, 86)
Explanation
perc[2:2] specifies an invalid range as start and stop
indexes are the same. Hence, an empty slice is stored in a.
Since stop index is not specified, perc[2:] will return a
tuple slice containing elements from index 2 to the last element.
Since start index is not specified, perc[:2] will return
a tuple slice containing elements from start to the element at index 1.
Length of Tuple is 6 and perc[:-2] implies to return a
tuple slice containing elements from start till perc[ : (6-2)] = perc[ : 4]
i.e., the element at index 3.
Length of Tuple is 6 and perc[-2: ] implies to return a
tuple slice containing elements from perc[(6-2): ] = perc[4 : ] i.e., from the
element at index 4 to the last element.
Length of Tuple is 6 and perc[2:-2] implies to return a
tuple slice containing elements from index 2 to perc[2:(6-2)] = perc[2 : 4]
i.e., to the element at index 3.
Length of Tuple is 6 and perc[-2: 2] implies to return a
tuple slice containing elements from perc[(6-2) : 2] = perc[4 : 2] i.e., index
at 4 to index at 2 but that will yield empty tuple as starting index has to be
lower than stopping index which is not true here.
It will return all the elements since start and stop
index is not specified.
Q 2
What does each of the following expressions evaluate to?
Suppose that T is the tuple containing :
("These", ["are" , "a",
"few", "words"] , "that", "we",
"will" , "use")
T[1][0: :2]
"a" in T[1][0]
T[:1] + [1]
T[2::2]
T[2][2] in T[1]
Ans.
The given expressions evaluate to the following:
['are', 'few']
True
TypeError: can only concatenate tuple (not
"list") to tuple
('that', 'will')
True
Explanation
T[1] represents first element of tuple i.e., the list
["are" , "a", "few", "words"]. [0 : :
2] creates a list slice starting from element at index zero of the list to the
last element including every 2nd element (i.e., skipping one element in between).
"in" operator is used to check elements
presence in a sequence. T[1] represents the list ["are" ,
"a", "few", "words"]. T[1][0] represents the
string "are". Since "a" is present in "are", it
returns true.
T[:1] is a tuple where as [1] is a list. They both can
not be concatenated with each other.
T[2::2] creates a tuple slice starting from element at
index two of the tuple to the last element including every 2nd element (i.e.,
skipping one element in between).
T[2] represents the string "that". T[2][2]
represents third letter of "that" i.e., "a". T[1]
represents the list ["are" , "a", "few",
"words"]. Since "a" is present in the list, the in operator
returns True.
Q 3(a)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ('a', 'b', 'c', 'd', 'e')
print(t[5])
Ans.
Output
IndexError: tuple index out of range
Explanation
Tuple t has 5 elements starting from index 0 to 4. t[5]
will throw an error since index 5 doesn't exist.
Q 3(b)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ('a', 'b', 'c', 'd', 'e')
t[0] = 'A'
Ans.
Output
TypeError: 'tuple' object does not support item
assignment
Explanation
Tuple is a collection of ordered and unchangeable items
as they are immutable. So once a tuple is created we can neither change nor add
new values to it.
Q 3(c)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t1 = (3)
t2 = (4, 5, 6)
t3 = t1 + t2
print (t3)
Ans.
Output
TypeError: unsupported operand type(s) for +: 'int' and
'tuple'
Explanation
t1 holds an integer value not a tuple since comma is not
added after the element where as t2 is a tuple. So here, we are trying to use +
operator with an int and tuple operand which results in this error.
Q 3(d)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t1 = (3,)
t2 = (4, 5, 6)
t3 = t1 + t2
print (t3)
Ans.
Output
(3, 4, 5, 6)
Explanation
t1 is a single element tuple since comma is added after
the element 3, so it can be easily concatenated with other tuple. Hence, the
code executes successfully without giving any errors.
Q 3(e)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t2 = (4,
5, 6)
t3 = (6,
7)
print(t3 - t2)
Ans.
Output
TypeError: unsupported operand type(s) for -: 'tuple' and
'tuple'
Explanation
Arithmetic operations are not defined in tuples. Hence we
can't remove items in a tuple.
Q 3(f)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t3 = (6, 7)
t4 = t3 * 3
t5= t3 * (3)
t6 = t3 * (3,)
print(t4)
print(t5)
print(t6)
Ans.
Output
TypeError: can't multiply sequence by non-int of type
'tuple'
Explanation
The repetition operator * replicates the tuple specified
number of times. The statements t3 * 3 and t3 * (3) are equivalent as (3) is an
integer not a tuple because of lack of comma inside parenthesis. Both the
statements repeat t3 three times to form tuples t4 and t5.
In the statement, t6 = t3 * (3,), (3,) is a single
element tuple and we can not multiply two tuples. Hence it will throw an error.
Q 3(g)
Carefully read the given code fragments and figure out
the errors that the code may produce.
odd= 1,3,5
print(odd + [2, 4, 6])[4]
Ans.
Output
TypeError: can only concatenate tuple (not
"list") to tuple
Explanation
Here [2,4,6] is a list and odd is a tuple so because of
different data types, they can not be concatenated with each other.
Q 3(h)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ( 'a', 'b', 'c', 'd', 'e')
1, 2, 3, 4, 5, = t
Ans.
Output
SyntaxError: cannot assign to literal
Explanation
When unpacking a tuple, the LHS (left hand side) should
contain a list of variables. In the statement, 1, 2, 3, 4, 5, = t, LHS is a
list of literals not variables. Hence, we get this error.
Q 3(i)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ( 'a', 'b', 'c', 'd', 'e')
1n, 2n, 3n, 4n, 5n = t
Ans.
Output
SyntaxError: invalid decimal literal
Explanation
This error occurs when we declare a variable with a name
that starts with a digit. Here, t is a tuple containing 5 values and then we
are performing unpacking operation of tuples by assigning tuple values to
1n,2n,3n,4n,5n which is not possible since variable names cannot start with
numbers.
Q 3(j)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ( 'a', 'b', 'c', 'd', 'e')
x, y, z, a, b = t
Ans.
Output
The code executes successfully without giving any errors.
After execution of the code, the values of the variables are:
x ⇒ a
y ⇒ b
z ⇒ c
a ⇒ d
b ⇒ e
Explanation
Here, Python assigns each of the elements of tuple t to
the variables on the left side of assignment operator. This process is called
Tuple unpacking.
Q 3(k)
Carefully read the given code fragments and figure out
the errors that the code may produce.
t = ( 'a', 'b', 'c', 'd', 'e')
a, b, c, d, e, f = t
Ans.
Output
ValueError: not enough values to unpack (expected 6, got
5)
Explanation
In tuple unpacking, the number of elements in the left
side of assignment must match the number of elements in the tuple.
Here, tuple t contains 5 elements where as left side
contains 6 variables which leads to mismatch while assigning values.
Q 4
What would be the output of following code if
ntpl = ("Hello", "Nita",
"How's", "life?")
(a, b, c, d) = ntpl
print ("a is:", a)
print ("b is:", b)
print ("c is:", c)
print ("d is:", d)
ntpl = (a, b, c, d)
print(ntpl[0][0]+ntpl[1][1], ntpl[1])
Ans.
Output
a is: Hello
b is: Nita
c is: How's
d is: life?
Hi Nita
Explanation
ntpl is a tuple containing 4 elements. The statement (a, b,
c, d) = ntpl unpacks the tuple ntpl into the variables a, b, c, d. After that,
the values of the variables are printed.
The statement ntpl = (a, b, c, d) forms a tuple with
values of variables a, b, c, d and assigns it to ntpl. As these variables were not
modified, so effectively ntpl still contains the same values as in the first
statement.
ntpl[0] ⇒ "Hello"
∴ ntpl[0][0] ⇒
"H"
ntpl[1] ⇒ "Nita"
∴ ntpl[1][1] ⇒"i"
ntpl[0][0] and ntpl[1][1] concatenates to form
"Hi". Thus ntpl[0][0]+ntpl[1][1], ntpl[1] will return "Hi Nita
".
Q 5
Predict the output.
tuple_a = 'a', 'b'
tuple_b = ('a',
'b')
print (tuple_a == tuple_b)
Ans.
Output
True
Explanation
Tuples can be declared with or without parentheses
(parentheses are optional). Here, tuple_a is declared without parentheses where
as tuple_b is declared with parentheses but both are identical. As both the
tuples contain same values so the equality operator ( == ) returns true.
Q 6
Find the error. Following code intends to create a tuple
with three identical strings. But even after successfully executing following
code (No error reported by Python), The len( ) returns a value different from
3. Why ?
tup1 = ('Mega') * 3
print(len(tup1))
Ans.
Output
12
Explanation
This is because tup1 is not a tuple but a string. To make
tup1 a tuple it should be initialized as following:
tup1 = ('Mega',) * 3
i.e., a comma should be added after the element.
We are getting 12 as output because the string
"Mega" has four characters which when replicated by three times
becomes of length 12.
Q 7
Predict the output.
tuple1 = ('Python') * 3
print(type(tuple1))
Ans.
Output
<class 'str'>
Explanation
This is because tuple1 is not a tuple but a string. To
make tuple1 a tuple it should be initialized as following:
tuple1 = ('Python',) * 3
i.e. a comma should be added after the element.
Q 8
Predict the output.
x = (1, (2, (3, (4,))))
print(len(x))
print( x[1][0] )
print( 2 in x )
y = (1, (2, (3,), 4), 5)
print( len(y) )
print( len(y[1]))
print( y[2] + 50 )
z = (2, (1, (2, ), 1), 1)
print( z[z[z[0]]])
Ans.
Output
2
2
False
3
3
55
(1, (2,), 1)
Explanation
print(len(x)) will return 2. x is a nested tuple
containing two elements — the number 1 and another nested tuple (2, (3, (4,))).
print( x[1] [0] ) Here, x[1] implies first element of
tuple which is (2,(3,(4,))) and x[1] [0] implies 0th element of x[1] i.e. 2 .
print( 2 in x ) "in" operator will search for
element 2 in tuple x and will return ""False"" since 2 is
not an element of parent tuple "x". Parent tuple "x" only
has two elements with x[0] = 1 and x[1] = (2, (3, (4,))) where x[1] is itself a
nested tuple.
y = (1, (2, (3,), 4), 5) y is a nested tuple containing
three elements — the number 1 , the nested tuple (2, (3,), 4) and the number 5.
Therefore, print( len(y) ) will return 3.
print( len(y[1])) will return "3". As y[1]
implies (2, (3,), 4). It has 3 elements — 2 (number), (3,) (tuple) and 4
(number).
print( y[2] + 50 ) prints "55". y[2] implies
second element of tuple y which is "5". Addition of 5 and 50 gives
55.
print( z[z[z[0]]]) will return (1, (2,), 1).
z[0] is equivalent to 2 i.e., first element of tuple z.
Now the expression has become z[z[2]] where z[2] implies
third element of tuple i.e. 1.
Now the expression has become z[1] which implies second
element of tuple i.e. (1, (2,), 1).
Q 9
What will the following code produce ?
Tup1 = (1,) * 3
Tup1[0] = 2
print(Tup1)
Ans.
Output
TypeError: 'tuple' object does not support item
assignment
Explanation
(1,) is a single element tuple. * operator repeats (1,)
three times to form (1, 1, 1) that is stored in Tup1.
Tup1[0] = 2 will throw an error, since tuples are
immutable. They cannot be modified in place.
Q 10
What will be the output of the following code snippet?
Tup1 = ((1, 2),) * 7
print(len(Tup1[3:8]))
Ans.
Output
4
Explanation
* operator repeats ((1, 2),) seven times and the
resulting tuple is stored in Tup1. Therefore, Tup1 will contain ((1, 2), (1,
2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2)).
Tup1[3:8] will create a tuple slice of elements from
index 3 to index 7 (excluding element at index 8) but Tup1 has total 7
elements, so it will return tuple slice of elements from index 3 to last
element i.e ((1, 2), (1, 2), (1, 2), (1, 2)).
len(Tup1[3:8]) len function is used to return the total
number of elements of tuple i.e., 4.
Type C: Programming Practice/Knowledge based Qs
Q 1
Write a Python program that creates a tuple storing first
9 terms of Fibonacci series.
Solution
lst = [0,1]
a = 0
b = 1
c = 0
for i in range(7):
c = a + b
a = b
b = c
lst.append(c)
tup = tuple(lst)
print("9 terms of Fibonacci series are:", tup)
Output
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)
Q 2(a)
Write a program that receives the index and returns the
corresponding value.
Solution
tup = eval(input("Enter the elements of
tuple:"))
b = int(eval(input("Enter the index value:")))
c = len(tup)
if b < c:
print("value of tuple at index", b ,"is:" ,tup[b])
else:
print("Index is out of range")
Output
Enter the elements of tuple: 1,2,3,4,5
Enter the index value: 3
value of tuple at index
3 is: 4
Q 2(b)
Write a program that receives a Fibonacci term and
returns a number telling which term it is. For instance, if you pass 3, it
returns 5, telling it is 5th term; for 8, it returns 7.
Solution
term = int(input ("Enter Fibonacci Term: "))
fib = (0,1)
while(fib[len(fib) - 1] < term):
fib_len =
len(fib)
fib = fib +
(fib[fib_len - 2] + fib[fib_len - 1],)
fib_len = len(fib)
if term == 0:
print("0
is fibonacci term number 1")
elif term == 1:
print("1
is fibonacci term number 2")
elif fib[fib_len - 1] == term:
print(term,
"is fibonacci term number", fib_len)
else:
print("The
term", term , "does not exist in fibonacci series")
Output
Enter Fibonacci Term: 8
8 is fibonacci term number 7
Q 3
Write a program to input n numbers from the user. Store
these numbers in a tuple. Print the maximum and minimum number from this tuple.
Solution
n = eval(input("Enter the numbers: "))
tup = tuple(n)
print("Tuple is:", tup)
print("Highest value in the tuple is:",
max(tup))
print("Lowest value in the tuple is:",
min(tup))
Output
Enter the numbers: 3,1,6,7,5
Tuple is: (3, 1, 6, 7, 5)
Highest value in the tuple is: 7
Lowest value in the tuple is: 1
Q 4
Write a program to create a nested tuple to store roll
number, name and marks of students.
Solution
tup = ()
ans = "y"
while ans == "y" or ans == "Y" :
roll_num =
int(input("Enter roll number of student: "))
name = input("Enter
name of student: ")
marks =
int(input("Enter marks of student: "))
tup +=
((roll_num, name, marks),)
ans =
input("Do you want to enter more marks? (y/n): ")
print(tup)
Output
Enter roll number of student: 1
Enter name of student: Shreya Bansal
Enter marks of student: 85
Do you want to enter more marks? (y/n): y
Enter roll number of student: 2
Enter name of student: Nikhil Gupta
Enter marks of student: 78
Do you want to enter more marks? (y/n): y
Enter roll number of student: 3
Enter name of student: Avni Dixit
Enter marks of student: 96
Do you want to enter more marks? (y/n): n
((1, 'Shreya Bansal', 85), (2, 'Nikhil Gupta', 78), (3,
'Avni Dixit', 96))
Q 5
Write a program that interactively creates a nested tuple
to store the marks in three subjects for five students, i.e., tuple will look
somewhat like :
marks( (45, 45, 40), (35, 40, 38), (36, 30, 38), (25, 27,
20), (10, 15, 20) )
Solution
num_of_students = 5
tup = ()
for i in range(num_of_students):
print("Enter the marks of student", i + 1)
m1 =
int(input("Enter marks in first subject: "))
m2 =
int(input("Enter marks in second subject: "))
m3 =
int(input("Enter marks in third subject: "))
tup = tup +
((m1, m2, m3),)
print()
print("Nested tuple of student data is:", tup)
Output
Enter the marks of student 1
Enter marks in first subject: 89
Enter marks in second subject: 78
Enter marks in third subject: 67
Enter the marks of student 2
Enter marks in first subject: 56
Enter marks in second subject: 89
Enter marks in third subject: 55
Enter the marks of student 3
Enter marks in first subject: 88
Enter marks in second subject: 78
Enter marks in third subject: 90
Enter the marks of student 4
Enter marks in first subject: 78
Enter marks in second subject: 67
Enter marks in third subject: 56
Enter the marks of student 5
Enter marks in first subject: 45
Enter marks in second subject: 34
Enter marks in third subject: 23
Nested tuple of student data is: ((89, 78, 67), (56, 89,
55), (88, 78, 90), (78, 67, 56), (45, 34, 23))
Q6. Write a program that interactively creates a nested
tuple to store the marks in three subjects for five students and also add a
function that computes total marks and average marks obtained by each student.
Tuple will look somewhat like :
marks( (45, 45, 40), (35, 40, 38),(36, 30, 38), (25, 27,
20), (10, 15, 20) )
Solution
num_of_students = 5
tup = ()
def totalAndAvgMarks(x):
total_marks =
sum(x)
avg_marks =
total_marks / len(x)
return
(total_marks, avg_marks)
for i in range(num_of_students):
print("Enter the marks of student", i + 1)
m1 =
int(input("Enter marks in first subject: "))
m2 =
int(input("Enter marks in second subject: "))
m3 =
int(input("Enter marks in third subject: "))
tup = tup + ((m1,
m2, m3),)
print()
print("Nested tuple of student data is:", tup)
for i in range(num_of_students):
print("The
total marks of student", i + 1,"=", totalAndAvgMarks(tup[i])[0])
print("The
average marks of student", i + 1,"=", totalAndAvgMarks(tup[i])[1])
print()
Output
Enter the marks of student 1
Enter marks in first subject: 25
Enter marks in second subject: 45
Enter marks in third subject: 45
Enter the marks of student 2
Enter marks in first subject: 90
Enter marks in second subject: 89
Enter marks in third subject: 95
Enter the marks of student 3
Enter marks in first subject: 68
Enter marks in second subject: 70
Enter marks in third subject: 56
Enter the marks of student 4
Enter marks in first subject: 23
Enter marks in second subject: 56
Enter marks in third subject: 45
Enter the marks of student 5
Enter marks in first subject: 100
Enter marks in second subject: 98
Enter marks in third subject: 99
Nested tuple of student data is: ((25, 45, 45), (90, 89,
95), (68, 70, 56), (23, 56, 45), (100, 98, 99))
The total marks of student 1 = 115
The average marks of student 1 = 38.333333333333336
The total marks of student 2 = 274
The average marks of student 2 = 91.33333333333333
The total marks of student 3 = 194
The average marks of student 3 = 64.66666666666667
The total marks of student 4 = 124
The average marks of student 4 = 41.333333333333336
The total marks of student 5 = 297
The average marks of student 5 = 99.0
Q 7
Write a program that inputs two tuples and creates a third,
that contains all elements of the first followed by all elements of the second.
Solution
tup1 = eval(input("Enter the elements of first
tuple: "))
tup2 = eval(input("Enter the elements of second
tuple: "))
tup3 = tup1 + tup2
print(tup3)
Output
Enter the elements of first tuple: 1,3,5,7,9
Enter the elements of second tuple: 2,4,6,8,10
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Q 8
Write a program as per following specification :
"'Return the length of the shortest string in the
tuple of strings str_tuple.
Precondition: the tuple will contain at least one
element."'
Solution
str_tuple = ("computer science with python"
,"Hello Python" ,"Hello World" ,"Tuples")
shortest_str = min(str_tuple)
shortest_str_len = len(shortest_str)
print("The length of shortest string in the tuple
is:", shortest_str_len)
Output
The length of shortest string in the tuple is: 12
Q 9(a)
Create a tuple containing the squares of the integers 1
through 50 using a for loop.
Solution
tup = ()
for i in range(1,51):
tup = tup +
(i**2,)
print("The square of integers from 1 to 50 is:"
,tup)
Output
The square of integers from 1 to 50 is: (1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121,
144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729,
784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681,
1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500)
Q 9(b)
Create a tuple ('a', 'bb', 'ccc', 'dddd', ... ) that ends
with 26 copies of the letter z using a for loop.
Solution
tup = ()
for i in range(1, 27):
tup = tup +
(chr(i + 96)* i,)
print(tup)
Output
('a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg',
'hhhhhhhh', 'iiiiiiiii', 'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll',
'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn', 'ooooooooooooooo', 'pppppppppppppppp',
'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr', 'sssssssssssssssssss',
'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu', 'vvvvvvvvvvvvvvvvvvvvvv',
'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx',
'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz')
Q 10
Given a tuple pairs = ((2, 5), (4, 2), (9, 8), (12, 10)),
count the number of pairs (a, b) such that both a and b are even.
Solution
tup = ((2,5),(4,2),(9,8),(12,10))
count = 0
tup_length = len(tup)
for i in range
(tup_length):
if tup [i][0] %
2 == 0 and tup[i][1] % 2 == 0:
count =
count + 1
print("The number of pair where both a and b are
even:", count)
Output
The number of pair where both a and b are even: 2
Q 11
Write a program that inputs two tuples seq_a and seq_b
and prints True if every element in seq_a is also an element of seq_b, else
prints False.
Solution
seq_a = eval(input("Enter the first tuple: "))
seq_b = eval(input("Enter the second tuple: "))
for i in seq_a:
if i not in
seq_b:
print("False")
break
else:
print("True")
Output
Enter the first tuple: 1,3,5
Enter the second tuple: 4,5,1,3
True
Q 12
Computing Mean. Computing the mean of values stored in a
tuple is relatively simple. The mean is the sum of the values divided by the
number of values in the tuple. That is,
�
ˉ
=
∑
�
�
;
∑
�
=
the sum of
�
,
�
=
number of elements
x
ˉ
=
N
∑x
;
∑x=the sum of x,
N=number of elements
Write a program that calculates and displays the mean of
a tuple with numeric elements.
Solution
tup = eval(input ("Enter the numeric tuple: "))
total = sum(tup)
tup_length = len(tup)
mean = total / tup_length
print("Mean of tuple:", mean)
Output
Enter the numeric tuple: 2,4,8,10
Mean of tuple: 6.0
Q 13
Write a program to check the mode of a tuple is actually
an element with maximum occurrences.
Solution
tup = eval(input("Enter a tuple: "))
maxCount = 0
mode = 0
for i in tup :
count =
tup.count(i)
if maxCount
< count:
maxCount = count
mode =
i
print("mode:", mode)
Output
Enter a tuple: 2,4,5,2,5,2
mode = 2
Q 14
Write a program to calculate the average of a tuple's
element by calculating its sum and dividing it with the count of the elements.
Then compare it with the mean obtained using mean() of statistics module.
Solution
import statistics
tup = eval(input("Enter a tuple: "))
tup_sum = sum(tup)
tup_len = len(tup)
print("Average of tuple element is:", tup_sum /
tup_len)
print("Mean of tuple element is:",
statistics.mean(tup))
Output
Enter a tuple: 2,3,4,5,6,7,8,9,10
Average of tuple element is: 6.0
Mean of tuple element is:
6
Q 15
Mean of means. Given a nested tuple tup1 = ( (1, 2), (3,
4.15, 5.15), ( 7, 8, 12, 15)). Write a program that displays the means of
individual elements of tuple tup1 and then displays the mean of these computed
means. That is for above tuple, it should display as :
Mean element 1 : 1. 5 ;
Mean element 2 : 4.1 ;
Mean element 3 : 10. 5 ;
Mean of means 5. 366666
Solution
tup1 = ((1, 2), (3, 4.15, 5.15), ( 7, 8, 12, 15))
total_mean = 0
tup1_len = len(tup1)
for i in range(tup1_len):
mean =
sum(tup1[i]) / len(tup1[i])
print("Mean element", i + 1, ":", mean)
total_mean =
total_mean + mean
print("Mean of means" ,total_mean / tup1_len)
Output
Mean element 1 : 1.5
Mean element 2 : 4.1000000000000005
Mean element 3 : 10.5
Mean of means 5.366666666666667
Comments
Post a Comment