Tuple Data Type in Python
What is Tuple Data Type?
Tuple
is special type of data structure in Python which is immutable. Immutable means
once you create tuple data type you cannot add, modify or delete tuple data items.
The tuple data items are enclosed within pair of parenthesis and separated with
comma.
·
Tuple is an ordered, immutable collection
of elements
·
which can be of different types
·
represented in pair of parenthesis and separated
with comma
·
immutable means once tuple is created its
contents cannot be changed
·
list is mutable means list items can be
inserted. modify or deleted
·
tuples are immutable means you cannot
insert or modify or delete tuple items once it is created
How to Create Tuple:
tuple1=(1,2,3)
print(tuple1)
Output:
(1,
2, 3)
Another
Example,
tuple2=(1,0,10.5,"hello")
print(tuple2)
Output:
(1,
0, 10.5, 'hello')
Methods of Tuple:
- Count():
Count
function returns the number of occurrences of a specified element in a tuple.
Example,
my_tuple=(1,2,3,4,5,4,5,4,5,4,5,5)
print(my_tuple.count(5))
Output:
5
2. Index():
Index
method returns the index of first occurrence of a specified element from tuple.
Example,
tuple1=(1,2,3,3,4,5,6,7,8,9)
print(tuple1.index(3))
Output:
2
3. Len():
Len()
returns numbers elements in a tuple
Example,
my_tuple=(1,2,3,4,5,6,7,8,9)
print(len(my_tuple))
Output:
9
4. Sorted():
The
sorted() returns the new tuple containing the sorted element of original tuple.
Example,
my_tuple=(1,22,33,4,5,6,0)
sorted_tuple=sorted(my_tuple)
print(my_tuple)
print(sorted_tuple)
Output:
(1,
22, 33, 4, 5, 6, 0)
[0,
1, 4, 5, 6, 22, 33]
Sorted()
returns the new tuple and cannot modify original tuple
my_tuple=(1,22,33,4,5,6,0)
sorted_tuple=sorted(my_tuple,reverse=True)
#reverse=True for descending order
print(my_tuple)
print(sorted_tuple)
Output:
(1,
22, 33, 4, 5, 6, 0)
[33,
22, 6, 5, 4, 1, 0]
5. Max():
The
max() returns the maximum value in the tuple
Example,
my_tuple=(1,2,3,4,5,6,20,50)
print(max(my_tuple))
Output:
50
6. Min():
The
min() returns the minimum value from tuple
Example,
my_tuple=(1,2,3,4,5,56,0)
print(min(my_tuple))
Output:
0
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏