Like list, tuple is a collection containing a group of homogeneous or heterogeneous data items.
Here like list, duplicate data items are allowed and insertion order is preserved.
The difference between List and Tuple is : List is mutable(changeable behavior) where as Tuple is immutable(non-changeable behavior).
In Tuple data items that we assign within a parenthesis.
t1=(100,12.34,True,'python',100) t1 Output: (100, 12.34, True, 'python', 100) #Memory required for tuple t1 import sys print(sys.getsizeof(t1)) Output: 88 #Length of tuple t1 len(t1) Output: 5
#Retrieve all data items from a tuple using for loop for k in t1: print(k) Output: 100 12.34 True python 100
#Access a particular data item through index value #Here like list index value starting from 0 to n-1 and -1 to -n t1 100 t1 'python' t1[-1] 100 t1[-2] 'python' See the following scenario: t2=('a') t3=('a','aa') t4=('a','aa','aaa') print(t2) print(t3) print(t4) Output: a ('a', 'aa') ('a', 'aa', 'aaa')
Here from the output we observed t2 is not considering as tuple by the control t2 is a string type of variable.
To make it tuple, we write t2=('a',) here simply a comma that we will add. Now the output is:
('a',) #which represents a tuple
#Another way to represent tuples t5=1, t6=1,2 t7=1,2,3 print(t5) print(t6) print(t7) Output: (1,) (1, 2) (1, 2, 3) #Tuple Assignment #(regdno, name, branch) s=(101,'Sanghamitra','CSE') regdno=s name=s branch=s print(regdno) print(name) print(branch) Output: 101 Sanghamitra CSE
Change Tuple Values
Once we create a tuple then we cannot change its values. Tuples are unchangeable, or immutable.
But we can convert the tuple into a list, change the list, and convert the list back into a tuple.
x = ("apple", 100, False) y = list(x) y = "python" x = tuple(y) print(x) Output: ('apple', 'python', False)
Remove items from tuple
Tuples are immutable, so we cannot remove items from it, but you can delete the tuple completely. We use del keyword to delete tuple completely.
t8 = ("orange", "apple", "banana")
print(t8) #this will raise an error because the tuple no longer exists.
#joining two tuples tuple1 = ("apple", "banana" , "cherry") tuple2 = (100, 200, 300) tuple3 = tuple1 + tuple2 print(tuple3) Output: ('apple', 'banana', 'cherry', 100, 200, 300)
#Create a tuple using tuple() constructor tuple4 = tuple((1000,False,34.56,'python',1000)) print(tuple4) Output: (1000, False, 34.56, 'python', 1000)
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc