0% found this document useful (0 votes)
6 views22 pages

Tuple

The document discusses the properties and operations of tuples in Python, including slicing, immutability, and the differences between tuples and lists. It explains how to create single-element and empty tuples, as well as how to unpack tuples and the implications of using the slice operator. Additionally, it covers the use of tuples in various scenarios and the limitations of certain operations like sum(), min(), and max() when applied to tuples.

Uploaded by

yaswanthmani422
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views22 pages

Tuple

The document discusses the properties and operations of tuples in Python, including slicing, immutability, and the differences between tuples and lists. It explains how to create single-element and empty tuples, as well as how to unpack tuples and the implications of using the slice operator. Additionally, it covers the use of tuples in various scenarios and the limitations of certain operations like sum(), min(), and max() when applied to tuples.

Uploaded by

yaswanthmani422
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Type A : Short Answer tuple[Start : Stop] ⇒ returns the

portion of the tuple from index Start


Questions/Conceptual to index Stop (excluding element at
Questions stop).
a[1:1] ⇒ This will return empty list
as a slice from index 1 to index 0 is
Question 1 an invalid range.
4. Both are creating tuple slice with
Discuss the utility and significance of tuples, elements falling between indexes
briefly. start and stop.
a[1:2] ⇒ (2,)
Answer It will return elements from index 1
to index 2 (excluding element at 2).
Tuples are used to store multiple items in a
a[1:1] ⇒ ()
single variable. It is a collection which is
a[1:1] specifies an invalid range as
ordered and immutable i.e., the elements of
start and stop indexes are the same.
the tuple can't be changed in place. Tuples
Hence, it will return an empty list.
are useful when values to be stored are
constant and need to be accessed quickly.
Question 3
Question 2 Does the slice operator always produce a
new tuple ?
If a is (1, 2, 3)
Answer
1. what is the difference (if any)
between a * 3 and (a, a, a) ? No, the slice operator does not always
2. Is a * 3 equivalent to a + a + a ? produce a new tuple. If the slice operator is
3. what is the meaning of a[1:1] ? applied on a tuple and the result is the same
4. what is the difference between a[1:2] tuple, then it will not produce a new tuple, it
and a[1:1] ? will return the same tuple as shown in the
example below:
Answer
a = (1, 2, 3)
print(a[:])
1. a * 3 ⇒ (1, 2, 3, 1, 2, 3, 1, 2, 3)
(a, a, a) ⇒ ((1, 2, 3), (1, 2, 3), (1, 2, Slicing tuple a using a[:] results in the same
3)) tuple. Hence, in this case, slice operator will
So, a * 3 repeats the elements of the not create a new tuple. Instead, it will return
tuple whereas (a, a, a) creates nested the original tuple a.
tuple.
2. Yes, both a * 3 and a + a + a will Question 4
result in (1, 2, 3, 1, 2, 3, 1, 2, 3).
3. This colon indicates (:) simple The syntax for a tuple with a single item is
slicing operator. Tuple slicing is simply the element enclosed in a pair of
basically used to obtain a range of matching parentheses as shown below :
items. t = ("a")
Is the above statement true? Why? Why not Answer
?
1. print("tuple") ⇒ tuple
Answer It will simply print the item inside
the print statement as it is of string
The statement is false. Single item tuple is type.
always represented by adding a comma after 2. print(tuple("tuple")) ⇒ it will throw
the item. If it is not added then python will error.
consider it as a string. TypeError: 'tuple' object is not
For example: callable
t1 = ("a",) This is because the variable "tuple"
print(type(t1)) ⇒ tuple is being used to define a tuple, and
t = ("a") then is being used again as if it were
print(type(t)) ⇒ string a function. This causes python to
throw the error as now we are using
Question 5 tuple object as a function but it is
already defined as a tuple.
Are the following two assignments same ? 3. print(tuple) ⇒ ('t', 'p', 'l')
Why / why not ? It will return the actual value of
1. tuple.

T1 = 3, 4, 5
Question 7
T2 = ( 3, 4 , 5)
How is an empty tuple created ?
2.
Answer
T3 = (3, 4, 5)
T4 = (( 3, 4, 5)) There are two ways of creating an empty
Answer tuple:

1. T1 and T2 are same. Both are tuples. 1. By giving no elements in parentheses


We can exclude/include the in assignment statement.
parentheses when creating a tuple Example:
with multiple values. emptyTuple = ()
2. T3 and T4 are not same. T3 is a tuple 2. By using the tuple function.
where as T4 is a nested tuple. Example:
emptyTuple = tuple()
Question 6
Question 8
What would following statements print?
Given that we have tuple= ('t', 'p', 'l') How is a tuple containing just one element
created ?
1. print("tuple")
2. print(tuple("tuple")) Answer
3. print(tuple) There are two ways of creating single
element tuple:
1. By enclosing the element in 1. When we want to ensure that data is
parentheses and adding a comma not changed accidentally. Tuples
after it. being immutable do not allow any
Example: t = (a,) changes in its data.
2. By using the built-in tuple type 2. When we want faster access to data
object (tuple( )) to create tuples from that will not change as tuples are
sequences: faster than lists.
Example: 3. When we want to use the data as a
t = tuple([1]) key in a dictionary. Tuples can be
Here, we pass a single element list to used as keys in a dictionary, but lists
the tuple function and get back a cannot.
single element tuple. 4. When we want to use the data as an
element of a set. Tuples can be used
Question 9 as elements of a set, but lists cannot.
How can you add an extra element to a tuple
? Question 11

What is the difference between (30) and


Answer
(30,) ?
We can use the concatenation operator to
add an extra element to a tuple as shown Answer
below. As tuples are immutable so they
a = (30) ⇒ It will be treated as an integer
cannot be modified in place.
expression, hence a stores an integer 30, not
For example: a tuple.
a = (30,) ⇒ It is considered as single
t=(1,2,3) element tuple since a comma is added after
t_append = t + (4,) the element to convert it into a tuple.
print(t)
print(t_append) Question 12
Output: When would sum( ) not work for tuples ?
(1,2,3) Answer
(1,2,3,4) Sum would not work for the following
cases:
Question 10
 When tuple does not have numeric
When would you prefer tuples over lists ? value.
For example:-
Answer tup = ("a", "b")
tup_sum = sum(tup)
Tuples are preferred over lists in the TypeError: unsupported operand
following cases: type(s) for +: 'int' and 'str'
here, "a" and "b" are string not integers Both in operator and [Link]( ) can be
therefore they can not be added together. used to search for an element in the tuple but
their working it is not exactly the same.
 Nested tuples having tuple as The "in" operator returns true or false
element. whereas [Link]() searches for a element
For example:- for the first occurrence and returns its
position. If the element is not found in tuple
a = (1,2,(3,4)) or the index function is called without
print(sum(a)) passing any element as a parameter then
Output: [Link]( ) raises an error:
TypeError: unsupported operand type(s)
for +: 'int' and 'tuple' For Example:-
Here, tuple 'a' is a nested tuple and since it tuple = (1, 3, 5, 7, 9)
consist of another tuple i.e. (3,4) it's print(3 in tuple) ⇒ True
elements can not be added to another tuple. print(4 in tuple) ⇒ False
Hence it will throw an error. print([Link](3)) ⇒ 1
print([Link](2)) ⇒ Error
 Tuple containing elements of
different data type. ValueError: [Link](x): x
For example:- not in tuple
print([Link]()) ⇒ Error
a = (1,2.5,(3,4),"hello")
print(sum(a)) TypeError: index expected at
Output: least 1 argument, got 0
TypeError: unsupported operand type(s)
for +: 'float' and 'tuple'
Question 15
Tuple a contains elements of integer, float,
string and tuple type which can not be added How are in operator and index( ) similar or
together. different ?

Question 13 Answer

Do min( ), max( ) always work for tuples ? Similarity:

Answer in operator and index( ) both search for a


value in tuple.
No, min( ), max( ) does not always work for
tuples. For min( ), max( ) to work, the Difference:
elements of the tuple should be of the same
type. in operator returns true if element exists in a
tuple otherwise returns false. While index( )
function returns the index of an existing
Question 14
element of the tuple. If the given element
Is the working of in operator and does not exist in tuple, then index( ) function
[Link]( ) same ? raises an error.

Answer
tuple. As you can see in the above example,
Type B: Application Based a will be 1, b will be 2, and c will be 3.
Questions
Question 1(c)
Question 1(a)
Find the output generated by following code
Find the output generated by following code fragments :
fragments :
(a, b, c, d) = (1, 2, 3)
plane = ("Passengers", Answer
"Luggage")
plane[1] = "Snakes" Output
Answer
ValueError: not enough values to
unpack (expected 4, got 3)
Output

TypeError: 'tuple' object does Explanation


not support item assignment
Tuple unpacking requires that the list of
variables on the left has the same number of
Explanation
elements as the length of the tuple. In this
Since tuples are immutable, tuple object case, the list of variables has one more
does not support item assignment. element than the length of the tuple so this
statement results in an error.
Question 1(b)
Question 1(d)
Find the output generated by following code
fragments : Find the output generated by following code
fragments :
(a, b, c) = (1, 2, 3)
a, b, c, d = (1, 2, 3)
Answer
Answer
Output
Output
a = 1
b = 2 ValueError: not enough values to
c = 3 unpack (expected 4, got 3)

Explanation
Explanation

When we put tuples on both sides of an Tuple unpacking requires that the list of
assignment operator, a tuple unpacking variables on the left has the same number of
operation takes place. The values on the elements as the length of the tuple. In this
right are assigned to the variables on the left case, the list of variables has one more
according to their relative position in each
element than the length of the tuple so this a, b, c, d, e = (p, q, r, s, t)
statement results in an error. = t1
What will be the values and types of
Question 1(e) variables a, b, c, d, e, p, q, r, s, t if t1
contains (1, 2.0, 3, 4.0, 5) ?
Find the output generated by following code
fragments : Answer
a, b, c, d, e = (p, q, r, s, t)
= t1 Variable

Answer
a
Output
b
Assuming t1 contains (1, 2.0, 3, 4.0, 5), the
output will be:
c
a = 1
p = 1 d
b = 2.0
q = 2.0 e

c = 3
p
r = 3

d = 4.0 q
s = 4.0
r
e = 5
t = 5
s
Explanation

The statement unpacks the tuple t1 into the t


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 Explanation
tuple unpacking. t1 is unpacked into each of
the variable lists a, b, c, d, e and p, q, r, s, t. The statement unpacks the tuple t1 into the
The corresponding variables of the two lists two variable lists given on the left of t1. The
will have the same value that is equal to the list of variables may or may not be enclosed
corresponding element of the tuple. in parenthesis. Both are valid syntax for
tuple unpacking. t1 is unpacked into each of
Question 1(f) 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 Find the output generated by following code
corresponding element of the tuple. fragments :

T4 = (17)
Question 1(g)
type(T4)
Find the output generated by following code Answer
fragments :

t2 = ('a') Output
type(t2)
<class 'int'>
Answer
Explanation
Output
Since no comma is added after the element,
<class 'str'> so even though it is enclosed in parenthesis
still it will be treated as an integer, hence T4
Explanation stores an integer not a tuple.

The type() function is used to get the type of Question 1(j)


an object. Here, 'a' is enclosed in parenthesis
but comma is not added after it, hence it is Find the output generated by following code
not a tuple and belong to string class. fragments :

T5 = (17,)
Question 1(h)
type(T5)
Find the output generated by following code Answer
fragments :

t3 = ('a',) Output
type(t3)
<class 'tuple'>
Answer
Explanation
Output
Since 17 is enclosed in parenthesis and a
<class 'tuple'> comma is added after it, so T5 becomes a
single element tuple instead of an integer.
Explanation
Question 1(k)
Since 'a' is enclosed in parenthesis and a
comma is added after it, so t3 becomes a Find the output generated by following code
single element tuple instead of a string. fragments :

tuple = ( 'a' , 'b', 'c' , 'd'


Question 1(i)
, 'e')
tuple = ( 'A', ) + tuple[1: ]
print(tuple) t3 = (6, 7)
t4 = t3 * 3
Answer t5 = t3 * (3)
print(t4)
Output print(t5)
('A', 'b', 'c', 'd', 'e') Answer

Explanation Output

tuple[1:] creates a tuple slice of elements (6, 7, 6, 7, 6, 7)


from index 1 (indexes always start from (6, 7, 6, 7, 6, 7)
zero) to the last element i.e. ('b', 'c',
'd', 'e'). Explanation
+ operator concatenates tuple ( 'A', ) and
tuple slice tuple[1: ] to form a new tuple. The repetition operator * replicates the tuple
specified number of times. The
Question 1(l) statements t3 * 3 and t3 * (3) are
equivalent as (3) is an integer not a tuple
Find the output generated by following code because of lack of comma inside
fragments : parenthesis. Both the statements
repeat t3 three times to form
t2 = (4, 5, 6) tuples t4 and t5.
t3 = (6, 7)
t4 = t3 + t2 Question 1(n)
t5 = t2 + t3
print(t4) Find the output generated by following code
print(t5) fragments :
Answer t1 = (3,4)
t2 = ('3' , '4')
Output print(t1 + t2 )
(6, 7, 4, 5, 6) Answer
(4, 5, 6, 6, 7)
Output
Explanation
(3, 4, '3', '4')
Concatenate operator concatenates the tuples
in the same order in which they occur to Explanation
form new tuple. t2 and t3 are concatenated
using + operator to form tuples t4 and t5. Concatenate operator + combines the two
tuples to form new tuple.
Question 1(m)
Question 1(o)
Find the output generated by following code
fragments :
What will be stored in variables a, b, c, d, e, 5. Length of Tuple is 6 and perc[-2:
f, g, h, after following statements ? ] implies to return a tuple slice
containing elements from perc[(6-
perc = (88,85,80,88,83,86) 2): ] = perc[4 : ] i.e., from the
a = perc[2:2] element at index 4 to the last
b = perc[2:] element.
c = perc[:2] 6. Length of Tuple is 6 and perc[2:-
d = perc[:-2] 2] implies to return a tuple slice
e = perc[-2:] containing elements from index 2
f = perc[2:-2] to perc[2:(6-2)] = perc[2 :
g = perc[-2:2] 4] i.e., to the element at index 3.
h = perc[:] 7. Length of Tuple is 6 and perc[-2:
2] implies to return a tuple slice
Answer containing elements from perc[(6-
2) : 2] = perc[4 : 2] i.e., index at
The values of variables a, b, c, d, e, f, g, h
4 to index at 2 but that will yield
after the statements will be:
empty tuple as starting index has to
a⇒() be lower than stopping index which
b ⇒ (80, 88, 83, 86) is not true here.
c ⇒ (88, 85) 8. It will return all the elements since
d ⇒ (88, 85, 80, 88) start and stop index is not specified.
e ⇒ (83, 86)
f ⇒ (80, 88) Question 2
g⇒()
h ⇒ (88, 85, 80, 88, 83, 86) What does each of the following expressions
evaluate to? Suppose that T is the tuple
Explanation containing :
("These", ["are" , "a", "few", "words"]
, "that", "we", "will" , "use")
1. perc[2:2] specifies an invalid range
as start and stop indexes are the 1. T[1][0: :2]
same. Hence, an empty slice is stored 2. "a" in T[1][0]
in a. 3. T[:1] + [1]
2. Since stop index is not 4. T[2::2]
specified, perc[2:] will return a 5. T[2][2] in T[1]
tuple slice containing elements from
index 2 to the last element. Answer
3. Since start index is not
specified, perc[:2] will return a The given expressions evaluate to the
tuple slice containing elements from following:
start to the element at index 1.
4. Length of Tuple is 6 and perc[:- 1. ['are', 'few']
2] implies to return a tuple slice 2. True
containing elements from start 3. TypeError: can only concatenate
till perc[ : (6-2)] = perc[ : tuple (not "list") to tuple
4] i.e., the element at index 3. 4. ('that', 'will')
5. True
Explanation Explanation

1. T[1] represents first element of tuple Tuple t has 5 elements starting from index 0
i.e., the list ["are" , "a", "few", to 4. t[5] will throw an error since index 5
"words"]. [0 : : 2] creates a list slice doesn't exist.
starting from element at index zero
of the list to the last element Question 3(b)
including every 2nd element (i.e.,
skipping one element in between). Carefully read the given code fragments and
2. "in" operator is used to check figure out the errors that the code may
elements presence in a sequence. produce.
T[1] represents the list ["are" , "a",
"few", "words"]. T[1][0] represents t = ('a', 'b', 'c', 'd', 'e')
the string "are". Since "a" is present t[0] = 'A'
in "are", it returns true. Answer
3. T[:1] is a tuple where as [1] is a list.
They both can not be concatenated Output
with each other.
TypeError: 'tuple' object does
4. T[2::2] creates a tuple slice starting not support item assignment
from element at index two of the
tuple to the last element including
Explanation
every 2nd element (i.e., skipping one
element in between). Tuple is a collection of ordered and
5. T[2] represents the string "that". unchangeable items as they are immutable.
T[2][2] represents third letter of So once a tuple is created we can neither
"that" i.e., "a". T[1] represents the change nor add new values to it.
list ["are" , "a", "few", "words"].
Since "a" is present in the list, the in
Question 3(c)
operator returns True.
Carefully read the given code fragments and
Question 3(a) figure out the errors that the code may
produce.
Carefully read the given code fragments and
figure out the errors that the code may t1 = (3)
produce. t2 = (4, 5, 6)
t3 = t1 + t2
t = ('a', 'b', 'c', 'd', 'e') print (t3)
print(t[5])
Answer Answer

Output Output

IndexError: tuple index out of TypeError: unsupported operand


range type(s) for +: 'int' and 'tuple'

Explanation
t1 holds an integer value not a tuple since TypeError: unsupported operand
comma is not added after the element where type(s) for -: 'tuple' and
as t2 is a tuple. So here, we are trying to use 'tuple'
+ operator with an int and tuple operand
which results in this error. Explanation

Question 3(d) Arithmetic operations are not defined in


tuples. Hence we can't remove items in a
Carefully read the given code fragments and tuple.
figure out the errors that the code may
produce. Question 3(f)
t1 = (3,) Carefully read the given code fragments and
t2 = (4, 5, 6) figure out the errors that the code may
t3 = t1 + t2 produce.
print (t3)
t3 = (6, 7)
Answer
t4 = t3 * 3
t5= t3 * (3)
Output t6 = t3 * (3,)
print(t4)
(3, 4, 5, 6)
print(t5)
print(t6)
Explanation Answer
t1 is a single element tuple since comma is
added after the element 3, so it can be easily Output
concatenated with other tuple. Hence, the
TypeError: can't multiply
code executes successfully without giving
sequence by non-int of type
any errors.
'tuple'

Question 3(e)
Explanation
Carefully read the given code fragments and
The repetition operator * replicates the tuple
figure out the errors that the code may specified number of times. The
produce. statements t3 * 3 and t3 * (3) are
equivalent as (3) is an integer not a tuple
t2 = (4, 5, 6)
because of lack of comma inside
t3 = (6, 7)
parenthesis. Both the statements
print(t3 - t2)
repeat t3 three times to form
Answer
tuples t4 and t5.
In the statement, t6 = t3 * (3,), (3,) is a
Output single element tuple and we can not multiply
two tuples. Hence it will throw an error.

Question 3(g)
Carefully read the given code fragments and Carefully read the given code fragments and
figure out the errors that the code may figure out the errors that the code may
produce. produce.

odd= 1,3,5 t = ( 'a', 'b', 'c', 'd', 'e')


print(odd + [2, 4, 6])[4] 1n, 2n, 3n, 4n, 5n = t
Answer Answer

Output Output

TypeError: can only concatenate SyntaxError: invalid decimal


tuple (not "list") to tuple literal

Explanation Explanation

Here [2,4,6] is a list and odd is a tuple so This error occurs when we declare a variable
because of different data types, they can not with a name that starts with a digit. Here, t is
be concatenated with each other. a tuple containing 5 values and then we are
performing unpacking operation of tuples by
Question 3(h) assigning tuple values
to 1n,2n,3n,4n,5n which is not possible
Carefully read the given code fragments and since variable names cannot start with
figure out the errors that the code may numbers.
produce.
Question 3(j)
t = ( 'a', 'b', 'c', 'd', 'e')
1, 2, 3, 4, 5, = t Carefully read the given code fragments and
Answer figure out the errors that the code may
produce.
Output
t = ( 'a', 'b', 'c', 'd', 'e')
SyntaxError: cannot assign to x, y, z, a, b = t
literal Answer

Explanation Output

When unpacking a tuple, the LHS (left hand The code executes successfully without
side) should contain a list of variables. In the giving any errors. After execution of the
statement, 1, 2, 3, 4, 5, = t, LHS is a code, the values of the variables are:
list of literals not variables. Hence, we get
this error. x ⇒ a
y ⇒ b
Question 3(i) z ⇒ c
a ⇒ d
b ⇒ e
Explanation Answer
Here, Python assigns each of the elements of
Output
tuple t to the variables on the left side of
assignment operator. This process is called a is: Hello
Tuple unpacking. b is: Nita
c is: How's
Question 3(k) d is: life?
Hi Nita
Carefully read the given code fragments and
figure out the errors that the code may
Explanation
produce.
ntpl is a tuple containing 4 elements. The
t = ( 'a', 'b', 'c', 'd', 'e') statement (a, b, c, d) = ntpl unpacks the
a, b, c, d, e, f = t tuple ntpl into the variables a, b, c, d. After
Answer that, the values of the variables are printed.
The statement ntpl = (a, b, c, d) forms a
Output tuple with values of variables a, b, c, d and
assigns it to ntpl. As these variables were
ValueError: not enough values to not modified, so effectively ntpl still
unpack (expected 6, got 5) contains the same values as in the first
statement.
Explanation ntpl[0] ⇒ "Hello"
∴ ntpl[0][0] ⇒ "H"
In tuple unpacking, the number of elements
in the left side of assignment must match the ntpl[1] ⇒ "Nita"
number of elements in the tuple. ∴ ntpl[1][1] ⇒"i"
Here, tuple t contains 5 elements where as
left side contains 6 variables which leads to ntpl[0][0] and ntpl[1][1] concatenates to
mismatch while assigning values. form "Hi". Thus ntpl[0][0]+ntpl[1][1],
ntpl[1] will return "Hi Nita ".
Question 4
Question 5
What would be the output of following code
if Predict the output.

ntpl = ("Hello", "Nita", tuple_a = 'a', 'b'


"How's", "life?") tuple_b = ('a', 'b')
(a, b, c, d) = ntpl print (tuple_a == tuple_b)
print ("a is:", a)
print ("b is:", b) Answer
print ("c is:", c)
print ("d is:", d) Output
ntpl = (a, b, c, d)
print(ntpl[0][0]+ntpl[1][1], True
ntpl[1])
Explanation
Tuples can be declared with or without Output
parentheses (parentheses are optional). Here,
tuple_a is declared without parentheses <class 'str'>
where as tuple_b is declared with
parentheses but both are identical. As both Explanation
the tuples contain same values so the
equality operator ( == ) returns true. This is because tuple1 is not a tuple but a
string. To make tuple1 a tuple it should be
initialized as following:
Question 6 tuple1 = ('Python',) * 3
i.e. a comma should be added after the
Find the error. Following code intends to
element.
create a tuple with three identical strings.
But even after successfully executing
following code (No error reported by Question 8
Python), The len( ) returns a value different
from 3. Why ? Predict the output.

tup1 = ('Mega') * 3 x = (1, (2, (3, (4,))))


print(len(tup1)) print(len(x))
Answer print( x[1][0] )
print( 2 in x )
y = (1, (2, (3,), 4), 5)
Output
print( len(y) )
12 print( len(y[1]))
print( y[2] + 50 )
z = (2, (1, (2, ), 1), 1)
Explanation
print( z[z[z[0]]])
This is because tup1 is not a tuple but a Answer
string. To make tup1 a tuple it should be
initialized as following:
tup1 = ('Mega',) * 3
Output
i.e., a comma should be added after the
2
element.
2
We are getting 12 as output because the
False
string "Mega" has four characters which
3
when replicated by three times becomes of
3
length 12.
55
(1, (2,), 1)
Question 7

Predict the output. Explanation

tuple1 = ('Python') * 3  print(len(x)) will return 2. x is a


print(type(tuple1)) nested tuple containing two elements
Answer — the number 1 and another nested
tuple (2, (3, (4,))).
 print( x[1] [0] ) Here, x[1] Output
implies first element of tuple which
is (2,(3,(4,))) and x[1] [0] implies TypeError: 'tuple' object does
0th element of x[1] i.e. 2 . not support item assignment
 print( 2 in x ) "in" operator will
search for element 2 in tuple x and Explanation
will return ""False"" since 2 is not an
element of parent tuple "x". Parent (1,) is a single element tuple. * operator
tuple "x" only has two elements repeats (1,) three times to form (1, 1, 1) that
with x[0] = 1 and x[1] = (2, (3, is stored in Tup1.
(4,))) where x[1] is itself a nested Tup1[0] = 2 will throw an error, since
tuple. tuples are immutable. They cannot be
 y = (1, (2, (3,), 4), 5) y is a modified in place.
nested tuple containing three
elements — the number 1 , the Question 10
nested tuple (2, (3,), 4) and the
number 5. Therefore, print( len(y) What will be the output of the following
) will return 3. code snippet?
 print( len(y[1])) will return "3".
As y[1] implies (2, (3,), 4). It has Tup1 = ((1, 2),) * 7
3 elements — 2 (number), (3,) print(len(Tup1[3:8]))
(tuple) and 4 (number).
Answer
 print( y[2] + 50 ) prints
"55". y[2] implies second element of
tuple y which is "5". Addition of 5 Output
and 50 gives 55.
4
 print( z[z[z[0]]]) will return (1,
(2,), 1).
z[0] is equivalent to 2 i.e., first Explanation
element of tuple z.
* operator repeats ((1, 2),) seven times
Now the expression has
become z[z[2]] where z[2] implies and the resulting tuple is stored in Tup1.
third element of tuple i.e. 1. Therefore, Tup1 will contain ((1, 2), (1,
2), (1, 2), (1, 2), (1, 2), (1, 2), (1,
Now the expression has
2)).
become z[1] which implies second
Tup1[3:8] will create a tuple slice of
element of tuple i.e. (1, (2,), 1).
elements from index 3 to index 7 (excluding
element at index 8) but Tup1 has total 7
Question 9 elements, so it will return tuple slice of
elements from index 3 to last element i.e ((1,
What will the following code produce ? 2), (1, 2), (1, 2), (1, 2)).
len(Tup1[3:8]) len function is used to
Tup1 = (1,) * 3 return the total number of elements of tuple
Tup1[0] = 2 i.e., 4.
print(Tup1)
Answer
Type C: Programming if b < c:
Practice/Knowledge based print("value of tuple at
Questions index", b ,"is:" ,tup[b])
else:
print("Index is out of
Question 1 range")

Write a Python program that creates a tuple Output


storing first 9 terms of Fibonacci series.
Enter the elements of tuple:
Solution 1,2,3,4,5
Enter the index value: 3
lst = [0,1] value of tuple at index 3 is:
a = 0 4
b = 1
c = 0
Question 2(b)
for i in range(7): Write a program that receives a Fibonacci
c = a + b term and returns a number telling which
a = b term it is. For instance, if you pass 3, it
b = c returns 5, telling it is 5th term; for 8, it
[Link](c) returns 7.

tup = tuple(lst) Solution

print("9 terms of Fibonacci term = int(input ("Enter


series are:", tup) Fibonacci Term: "))

Output fib = (0,1)

9 terms of Fibonacci series are: while(fib[len(fib) - 1] < term):


(0, 1, 1, 2, 3, 5, 8, 13, 21) fib_len = len(fib)
fib = fib + (fib[fib_len -
Question 2(a) 2] + fib[fib_len - 1],)

Write a program that receives the index and fib_len = len(fib)


returns the corresponding value.
if term == 0:
Solution print("0 is fibonacci term
number 1")
tup = eval(input("Enter the elif term == 1:
elements of tuple:")) print("1 is fibonacci term
b = int(eval(input("Enter the number 2")
index value:"))) elif fib[fib_len - 1] == term:
c = len(tup)
print(term, "is fibonacci Solution
term number", fib_len)
else: tup = ()
print("The term", term ,
"does not exist in fibonacci ans = "y"
series") while ans == "y" or ans == "Y" :
roll_num =
int(input("Enter roll number of
Output
student: "))
Enter Fibonacci Term: 8 name = input("Enter name
8 is fibonacci term number 7 of student: ")
marks = int(input("Enter
marks of student: "))
Question 3 tup += ((roll_num, name,
Write a program to input n numbers from marks),)
the user. Store these numbers in a tuple. ans = input("Do you want
Print the maximum and minimum number to enter more marks? (y/n): ")
from this tuple. print(tup)

Solution Output

n = eval(input("Enter the Enter roll number of student: 1


numbers: ")) Enter name of student: Shreya
Bansal
tup = tuple(n) Enter marks of student: 85
Do you want to enter more marks?
print("Tuple is:", tup) (y/n): y
print("Highest value in the Enter roll number of student: 2
tuple is:", max(tup)) Enter name of student: Nikhil
print("Lowest value in the tuple Gupta
is:", min(tup)) Enter marks of student: 78
Do you want to enter more marks?
(y/n): y
Output
Enter roll number of student: 3
Enter the numbers: 3,1,6,7,5 Enter name of student: Avni
Tuple is: (3, 1, 6, 7, 5) Dixit
Highest value in the tuple is: 7 Enter marks of student: 96
Lowest value in the tuple is: 1 Do you want to enter more marks?
(y/n): n
((1, 'Shreya Bansal', 85), (2,
Question 4 'Nikhil Gupta', 78), (3, 'Avni
Dixit', 96))
Write a program to create a nested tuple to
store roll number, name and marks of
students. Question 5
Write a program that interactively creates a Enter marks in third subject: 90
nested tuple to store the marks in three
subjects for five students, i.e., tuple will Enter the marks of student 4
look somewhat like : Enter marks in first subject: 78
marks( (45, 45, 40), (35, 40, 38), (36, 30, Enter marks in second subject:
38), (25, 27, 20), (10, 15, 20) ) 67
Enter marks in third subject: 56
Solution
Enter the marks of student 5
num_of_students = 5 Enter marks in first subject: 45
tup = () Enter marks in second subject:
34
Enter marks in third subject: 23
for i in range(num_of_students):
print("Enter the marks of Nested tuple of student data is:
student", i + 1) ((89, 78, 67), (56, 89, 55),
m1 = int(input("Enter marks (88, 78, 90), (78, 67, 56), (45,
in first subject: ")) 34, 23))
m2 = int(input("Enter marks
in second subject: ")) Question 6
m3 = int(input("Enter marks
in third subject: ")) Write a program that interactively creates a
tup = tup + ((m1, m2, m3),) nested tuple to store the marks in three
print() subjects for five students and also add a
function that computes total marks and
print("Nested tuple of student average marks obtained by each student.
data is:", tup) Tuple will look somewhat like :
marks( (45, 45, 40), (35, 40, 38),(36, 30,
Output 38), (25, 27, 20), (10, 15, 20) )

Enter the marks of student 1 Solution


Enter marks in first subject: 89
Enter marks in second subject: num_of_students = 5
78 tup = ()
Enter marks in third subject: 67
def totalAndAvgMarks(x):
Enter the marks of student 2 total_marks = sum(x)
Enter marks in first subject: 56 avg_marks = total_marks /
Enter marks in second subject: len(x)
89 return (total_marks,
Enter marks in third subject: 55 avg_marks)

Enter the marks of student 3 for i in range(num_of_students):


Enter marks in first subject: 88 print("Enter the marks of
Enter marks in second subject: student", i + 1)
78
m1 = int(input("Enter marks
in first subject: ")) Enter the marks of student 5
m2 = int(input("Enter marks Enter marks in first subject:
in second subject: ")) 100
m3 = int(input("Enter marks Enter marks in second subject:
in third subject: ")) 98
tup = tup + ((m1, m2, m3),) Enter marks in third subject: 99
print()
Nested tuple of student data is:
print("Nested tuple of student ((25, 45, 45), (90, 89, 95),
data is:", tup) (68, 70, 56), (23, 56, 45),
(100, 98, 99))
for i in range(num_of_students): The total marks of student 1 =
print("The total marks of 115
student", i + 1,"=", The average marks of student 1 =
totalAndAvgMarks(tup[i])[0]) 38.333333333333336
print("The average marks of
student", i + 1,"=", The total marks of student 2 =
totalAndAvgMarks(tup[i])[1]) 274
print() The average marks of student 2 =
91.33333333333333
Output
The total marks of student 3 =
Enter the marks of student 1 194
Enter marks in first subject: 25 The average marks of student 3 =
Enter marks in second subject: 64.66666666666667
45
Enter marks in third subject: 45 The total marks of student 4 =
124
Enter the marks of student 2 The average marks of student 4 =
Enter marks in first subject: 90 41.333333333333336
Enter marks in second subject:
89 The total marks of student 5 =
Enter marks in third subject: 95 297
The average marks of student 5 =
Enter the marks of student 3 99.0
Enter marks in first subject: 68
Enter marks in second subject: Question 7
70
Enter marks in third subject: 56 Write a program that inputs two tuples and
creates a third, that contains all elements of
Enter the marks of student 4 the first followed by all elements of the
Enter marks in first subject: 23 second.
Enter marks in second subject:
56 Solution
Enter marks in third subject: 45
tup1 = eval(input("Enter the Solution
elements of first tuple: "))
tup2 = eval(input("Enter the tup = ()
elements of second tuple: ")) for i in range(1,51):
tup3 = tup1 + tup2 tup = tup + (i**2,)
print(tup3) print("The square of integers
from 1 to 50 is:" ,tup)
Output
Output
Enter the elements of first
tuple: 1,3,5,7,9 The square of integers from 1 to
Enter the elements of second 50 is: (1, 4, 9, 16, 25, 36,
tuple: 2,4,6,8,10 49, 64, 81, 100, 121, 144, 169,
(1, 3, 5, 7, 9, 2, 4, 6, 8, 10) 196, 225, 256, 289, 324, 361,
400, 441, 484, 529, 576, 625,
676, 729, 784, 841, 900, 961,
Question 8 1024, 1089, 1156, 1225, 1296,
Write a program as per following 1369, 1444, 1521, 1600, 1681,
specification : 1764, 1849, 1936, 2025, 2116,
2209, 2304, 2401, 2500)
"'Return the length of the shortest string in
the tuple of strings str_tuple. Question 9(b)
Precondition: the tuple will contain at least
one element."' Create a tuple ('a', 'bb', 'ccc', 'dddd', ... ) that
ends with 26 copies of the letter z using a for
Solution loop.

str_tuple = ("computer science Solution


with python" ,"Hello Python"
,"Hello World" ,"Tuples") tup = ()
shortest_str = min(str_tuple) for i in range(1, 27):
shortest_str_len = tup = tup + (chr(i + 96)*
len(shortest_str) i,)
print("The length of shortest print(tup)
string in the tuple is:",
shortest_str_len) Output

Output ('a', 'bb', 'ccc', 'dddd',


'eeeee', 'ffffff', 'ggggggg',
The length of shortest string in 'hhhhhhhh', 'iiiiiiiii',
the tuple is: 12 'jjjjjjjjjj', 'kkkkkkkkkkk',
'llllllllllll', 'mmmmmmmmmmmmm',
Question 9(a) 'nnnnnnnnnnnnnn',
'ooooooooooooooo',
Create a tuple containing the squares of the 'pppppppppppppppp',
integers 1 through 50 using a for loop. 'qqqqqqqqqqqqqqqqq',
'rrrrrrrrrrrrrrrrrr', seq_b = eval(input("Enter the
'sssssssssssssssssss', second tuple: "))
'tttttttttttttttttttt',
'uuuuuuuuuuuuuuuuuuuuu', for i in seq_a:
'vvvvvvvvvvvvvvvvvvvvvv', if i not in seq_b:
'wwwwwwwwwwwwwwwwwwwwwww', print("False")
'xxxxxxxxxxxxxxxxxxxxxxxx', break
'yyyyyyyyyyyyyyyyyyyyyyyyy', else:
'zzzzzzzzzzzzzzzzzzzzzzzzzz') print("True")

Question 10 Output

Given a tuple pairs = ((2, 5), (4, 2), (9, 8), Enter the first tuple: 1,3,5
(12, 10)), count the number of pairs (a, b) Enter the second tuple: 4,5,1,3
such that both a and b are even. True

Solution Question 12

tup = Computing Mean. Computing the mean of


((2,5),(4,2),(9,8),(12,10)) values stored in a tuple is relatively simple.
count = 0 The mean is the sum of the values divided
tup_length = len(tup) by the number of values in the tuple. That is,
for i in range (tup_length):
if tup [i][0] % 2 == 0 and xˉ=∑xN;∑x=the sum of x,N=numbe
tup[i][1] % 2 == 0: r of elementsxˉ=N∑x
count = count + 1 ;∑x=the sum of x,N=number of elem
print("The number of pair where
both a and b are even:", count)
ents
Write a program that calculates and displays
Output the mean of a tuple with numeric elements.
The number of pair where both a
Solution
and b are even: 2
tup = eval(input ("Enter the
Question 11 numeric tuple: "))

Write a program that inputs two tuples seq_a total = sum(tup)


and seq_b and prints True if every element tup_length = len(tup)
in seq_a is also an element of seq_b, else mean = total / tup_length
prints False.
print("Mean of tuple:", mean)
Solution
Output
seq_a = eval(input("Enter the
first tuple: "))
Enter the numeric tuple:
2,4,8,10 print("Average of tuple element
Mean of tuple: 6.0 is:", tup_sum / tup_len)
print("Mean of tuple element
Question 13 is:", [Link](tup))

Write a program to check the mode of a Output


tuple is actually an element with maximum
occurrences. Enter a tuple:
2,3,4,5,6,7,8,9,10
Solution Average of tuple element is:
6.0
tup = eval(input("Enter a tuple: Mean of tuple element is: 6
"))
maxCount = 0 Question 15
mode = 0
Mean of means. Given a nested tuple tup1
for i in tup : = ( (1, 2), (3, 4.15, 5.15), ( 7, 8, 12, 15)).
count = [Link](i) Write a program that displays the means of
if maxCount < count: individual elements of tuple tup1 and then
maxCount = count displays the mean of these computed means.
mode = i That is for above tuple, it should display as :
Mean element 1 : 1. 5 ;
print("mode:", mode) Mean element 2 : 4.1 ;
Mean element 3 : 10. 5 ;
Output Mean of means 5. 366666

Enter a tuple: 2,4,5,2,5,2 Solution


mode = 2
tup1 = ((1, 2), (3, 4.15, 5.15),
Question 14 ( 7, 8, 12, 15))
total_mean = 0
Write a program to calculate the average of tup1_len = len(tup1)
a tuple's element by calculating its sum and
dividing it with the count of the elements. for i in range(tup1_len):
Then compare it with the mean obtained mean = sum(tup1[i]) /
using mean() of statistics module. len(tup1[i])
print("Mean element", i + 1,
Solution ":", mean)
total_mean = total_mean +
import statistics mean

tup = eval(input("Enter a tuple: print("Mean of means"


")) ,total_mean / tup1_len)
tup_sum = sum(tup)
tup_len = len(tup)

You might also like