Tuple in Python Class 11 Easy Notes
What is Tuple in Python
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuple: It is a sequence of immutable objects. It is just like list. Difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Lists uses square bracket whereas tuples use parentheses.
Creating A Tuple:
A tuple is enclosed in parentheses () for creation and each item is separated by a comma.
tup1 = (‘comp sc’, ‘info practices’, 2017, 2018)
tup2 = (5,11,22,44)
Indexing of tuple is just similar to indexing of list.
Accessing Values from Tuples
Use the square brackets for slicing along with the index or indices to obtain the value available at that index.
tup1 = (“comp sc”, “info practices”, 2017, 2018)
tup2 = (5,11,22,44,9,66)
print (“tup1: “, tup1)
print (“tup2[1:5]: “, tup2[1:5])
(‘tup1: ‘, ‘comp sc’)
(‘tup2[1:5]: ‘, (11, 22, 44, 9))
Iterating Through A Tuple
Element of the tuple can be accessed sequentially using loop.
tup = (5,11,22)
for i in range(0,len(tup)):
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.
tup1 = (1, 2)
tup2 = (‘a’, ‘b’)
tup3 = tup1 + tup2
(1, 2, ‘a’, ‘b’)
Delete Tuple Elements
Direct deletion of tuple element is not possible but shifting of required content after discard of unwanted content to another tuple.
tup1 = (1, 2,3)
tup3 = tup1[0:1] + tup1[2:]
Output (1, 3)
NOTE : Entire tuple can be deleted using del statement.
Basic Tuples Operations
|len((1, 2, 3, 4))||4||Length|
|(1, 2, 3)+(4,5,6)||(1,2,3,4,5,6)||Concatenation|
|4 in (1, 2, 3, 4)||True||Membership|
|for i in (1,2,3) :
|1||tuple(seq)||Converts a list into tuple.|
|2||min(tuple)||Returns item from the tuple with min value.|
|3||max(tuple)||Returns item from the tuple with max value.|
|4||len(tuple)||Gives the total length of the tuple.|
|5||cmp||(tuple1, tuple2) Compares elements of both tuples.|