Python Tuples
- Categories Python Tuple, Python
In this post we will cover Tuples in Python. You can watch our videos on Tuples in Python – Click Here
Q.1 What is Tuple in python? Also give an example.
Ans.
- Tuples are a collection of data items. They may be of different types.
- Tuples are immutable like strings. Lists are like tuples but are mutable.
- e.g. T= (“Tony”, “Pat”, “Stewart”)
(‘Tony’, ‘Pat’, ‘Stewart’) - Python uses () to denote tuples; we could also use (), but if we have only one item, we need to use a comma to indicate it’s a tuple: (“Tony”,).
- An empty tuple is denoted by ()
Q. 2 How to create a python Tuple?
Ans.
- To create a new Python Tuple, you can either assign empty round brackets T=( )
- You can also assign any values directly inside round brackets separated by comma.
T= T = ( val1, val2,val3, val4….) - You can also create tuple as user input
- L = tuple (input (“Enter tuple”))
- L = eval (input (“Enter tuple”))
- Do note that indexing of tuple is just similar to indexing of list.
Q.3 How to accessing values from tuples?
Ans. To Accessing Values from Tuples
- Use the square brackets for slicing along with the index
- or indices to obtain the value available at that index.
- e.g.
tup1 = (“comp sc”, “info practices”, 2020, 2021)
tup2 = (5,8,20,4,9,56)
print (“tup1[0]: “, tup1[0])
print (“tup2[1:5]: “, tup2[1:5])
Q. 4 How to update Tuples?
Ans. To updating Tuples:
- Tuples are immutable so 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. Or convert to list and then back.
- E.g.
tup1 = (1, 2)
tup2 = (‘a’, ‘b’)
tup3 = tup1 + tup2
print (tup3)
Q.5 How we can delete tuple elements?
Ans.
- Direct deletion of tuple element is not possible but shifting of required content after discard of unwanted content to another tuple.
- Entire tuple can be deleted using del statement. e.g. del tup1
- E.g.
tup1 = (1, 2,3)
tup3 = tup1[0:1] + tup1[2:]
print (tup3) - Output
(1, 3)
Q. 6 What is tuple slicing?
Ans. Slice operator works on Tuple also.
- It is used to display more than one selected value on the output screen.
- Slices are treated as boundaries and the result will contain all the elements between boundaries.
- Syntax: Seq = T [start: stop: step]
- Where start, stop & step – all three are optional. If we omit first index, slice starts from ‘0’. On omitting stop, slice will take it to end. Default value of step is 1.
Q. 7 What is differentiate between tuple and list?
Ans. List Tuples List is mutable. Tuple is immutable. List iteration is slower and is time consuming. Tuple iteration is faster. List is useful for insertion and deletion operations. Tuple is useful for readonly operations like accessing elements. List consumes more memory. Tuples consumes less memory. List provides many in-built methods. Tuples have less in-built methods. List operations are more error prone. Tuples operations are safe.
Q. 8 Write any 2 tuple functions and method with description.
Ans.
Method:
- count(): Returns the number of times a specified value occurs in a tuple
- index(): Searches the tuple for a specified value and returns the position of where it was found
Q. 9 Write a Python program to test if a variable is a list or tuple or a set.
Ans.
#x = ['a', 'b', 'c', 'd']
#x = {'a', 'b', 'c', 'd'}
x = ('tuple', False, 3.2, 1)
if type(x) is list:
print('x is a list')
elif type(x) is set:
print('x is a set')
elif type(x) is tuple:
print('x is a tuple')
else:
print('Neither a list or a set or a tuple.')
Q.10 Write a Python program to sort a list of tuples by the second Item.
Ans.
def Sort_Tuple(tup):
lst = len(tup)
for i in range(0, lst):
for j in range(0, lst-i-1):
if (tup[j][1] > tup[j + 1][1]):
temp = tup[j]
tup[j]= tup[j + 1]
tup[j + 1]= temp
return tup
tup =[('for', 2), ('is', 9), ('to', 7),('Go', 5), ('or', 15), ('a', 13)]
print(Sort_Tuple(tup))
Q.11 Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
Ans.
values = input("Input some comma separated numbers : ")
list = values.split(",")
tuple = tuple(list)
print('List : ',list)
print('Tuple : ',tuple)
Q. 12 Write a python program to print sum of tuple elements.
Ans.
test_tup = (7, 5, 9, 1, 10, 3)
print("The original tuple is : " + str(test_tup))
res = sum(list(test_tup))
# printing result
print("The sum of all tuple elements are : " + str(res))
Q. 13 Write a Python program to sort a list of tuples alphabetically
Ans.
def SortTuple(tup):
n = len(tup)
for i in range(n):
for j in range(n-i-1):
if tup[j][0] > tup[j + 1][0]:
tup[j], tup[j + 1] = tup[j + 1], tup[j]
return tup
tup = [("Amaruta", 20), ("Zoe", 32), ("Akshay", 25),("Nilesh", 21), ("C", "D"), ("Penny", 22)]
print(SortTuple(tup))
Q. 14 Write a python program to Check if the given element is present in tuple or not.
Ans.
test_tup = (10, 4, 5, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
N = int(input("value to be checked:"))
res = False
for ele in test_tup :
if N == ele :
res = True
break
print("Does contain required value ? : " + str(res))