Tuples in Python
Tuples in Python
A tuple is a python sequence which stores a group elements or items. Tuples are similar to lists but the main difference between tuple and lists are, tuple is immutable means that there are no modifications after its creation whereas lists are mutable means that modifications takes place after its creation. Hence we can not perform append(), insert(), pop(),remove() on tuples.
>>> tu=()
>>> type(tu)
<class 'tuple'>
>>> tu=(11,22,33,44,55)
>>> tu
(11, 22, 33, 44, 55)
>>> tu[2]
33
>>> tu[3]
44
Functions to process tuples
len(nameofthetuple)-returns the number of elements in the tuple
>>> len(tu1)
9
min(tuplename)-returns the minimum element in the tuple
>>> min(tu1)
11
max(tuplename)-returns the maximum element in the tuple
>>> max(tu1)
99
sum(tuplename)-returns the sum of all the elements in the tuple
>>> sum(tu1)
495
sorted(tuplename)-prints the list of tuple elements in sorted order
>>> sorted(tu1)
[11, 22, 33, 44, 55, 66, 77, 88, 99]
Methods to process tuples
>>> tu2=(11,22,33,11,22,55,44)
count(tuplename)-returns the number of occurrences of an element in the tuple.
>>> tu2.count(22)
2
index(tuplename)-returns the position of element located in the tuple
>>> tu2.index(22)
1
Watch the video for better understanding
Comments
Post a Comment