80 likes | 81 Views
A tuple is a collection that is ordered andu00a0unchangeable.<br>Tuples are written with round brackets or a tuple is a collection of Python objects separated by commas. A different feature of the tuple and the methods to handle the tuple and its methods are discussed in detail in this tutorial.<br> To learn more about Tuple, IBM certified data science courses or online data science courses, Visit: http://bit.ly/DatascienceCourse<br>or Follow us on our social media platforms mentioned in the above document.
E N D
Tuple • Tuple is similar to list .The only difference is that tuple is immutable whereas list is mutable. • So we cannot use methods such as append or remove due to its immutability. Hence, item assignment is also not possible. • A tuple is a collection which is ordered and unchangeable. • Tuples are written with round brackets or a tupleis a collection of Python objects separated by commas.
Creating a tuple • Creating an empty tuple:tup= () print (tup)O/P: () • Creating a non empty tuple:There are two ways to create non empty tuple. • tup= ‘Learnbay‘, ’class’print(tup) O/P: (‘Learnbay', ‘class') • tup= (‘Learnbay', ‘class') print(tup)O/P: (‘Learnbay', ‘class')
Tuple Methods • count():counts the number of times an element or a value is repeated in tuple. • Eg:tpl=(1,10,20,1,10,20,40,1,60,100,1) print(tpl.count(1))O/P:4 • index():gives the index of the stated valueEg:print(tpl.index(40))O/P: 6
Removing an element from tuple • As tuple is immutable directly removing an element is not possible.Thus,generally we convert it into the list perform the operation and convert it back to tuple. • Eg: tpl=(1,10,20,1,10,20,40,1,60,100,1)lst=list(tpl)lst.remove(20)out_tpl=tuple(lst) print(out_tpl)O/P: =(1,10,1,10,20,40,1,60,100,1)
Tuple Packing:packing multiple values into a single variable • Eg: a = 10 b = 20 c = 30 d = 40tpl = a,b,c,d print(tpl)O/P:(10, 20, 30, 40)
Tuple Unpacking • unpacking a tuple into multiple variables • Eg: tpl = 1,10,100,20,10,1a,b,c,d,e,f,g = tpl print(a) print(b) print(c) print(d) print(e) print(f) • O/P: 1 10 100 20 10 1
THANKS FOR WATCHING! • For more such content visit: http://bit.ly/DatascienceCourse • Or follow us on our social media platforms: • Facebook: Learnbay • Instagram: Learnbay_datascience • Twitter: Learnbay1 • LiknkedIn: Learnbay • Youtube (Tutorials): https://www.youtube.com/channel/UC-ntE_GnjjiUuKYqih9ENYA