Tuples Notes (Python)
Tuples Notes (Python)
Answer =
It is a type of arrays . it play very important role in python . in python it is immutable
type of container which store any kind of data types it is short in memory size in
comparison of list
.
Q. 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] ?
Answer =
A = a*3 will print three times of tuple in a single tuple
>>>(1,2,3,1,2,3,1,2,3)
(a,a,a) will print nested tuple.
>>>((1,2,3),(1,2,3),(1,2,3))
B = yes
C = it mean that it will not give any e value because it is start from index number 1
but stop at index number 1 but as we know that in slicing it is start from 1 and stop
up at 1 so it will print empty tuple.
D = a[1:2] will print value at index number 1 while,
a[1:1] will print empty tuple.
Q.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 ?
ANSWER =
No, it not true because when we use type function then it will print 'str' type ,it can be
corrected by adding comma (,)
ANSWER =A t1==t2
>>> True
Because t1 and t2 have same value.
B t3 == t4
>>> False
Because T3 have a tuple but T4 have a nested tuple.
Q. What would following statements print ? Given that we have tuple = ('t', 'p',
'I') (a) print("tuple")
(b) print(tuple(“tuple"))
(c) print (tuple)
ANSWER =
A = 'tuple'
B = ('t','u','p','l','e')
C = ('t','p','l')
Answer =
By two way we can create a empty tuple first by given value with out any value
Like :- a =()
Second by defining tuple
A=tuple ()
Example:- a=('p','y','t','h','o')
b =('n')
print (a+b)
>>>('p','y','t','h','o','n')
Q. When would you prefer tuples over lists ?
Answer =
We would prefer tuple over list due to following reason .
1 tuple is faster than list.
2 tuple can use as a key in a dictionary while in list not possible.
3 tuple is immutable and list is mutable.
Q. What is the difference between (30) and (30,)?
Answer =
When we use type function then (30) is type of 'int' class where (30,) is a type of
tuple which contain one element.
Q. When would sum() not work for tuples?
Answer =
When tuple does not have numeric value.
Q. Do min( ), max( ) always work for tuples?
Answer =
No, if tuple have same types of data-types then these functions work.
Q. Is the working of in operator and tuple.index() same?
Answer =
Yes, their works is similar but not same.
Q. How are in operator and index() similar or different?
Answer =
Similarity:-
in operator and index() both are similar because they tells existence of
element in tuple.
Difference:-
in operator return true if element exist in a tuple otherwise return false. While
index() function returns the index of an existing element of the tuple. But if the
given items does not exist in tuple, then it raise error.