>>> data=(10,20,'Ramana',63.8)
>>> data2="a",10,20.9
>>> data
(10, 20, 'Ramana', 63.8)
>>> data2
('a', 10, 20.9)
>>>
>>> tuple_1='a','Ramana',36.18
>>> tuple_2=tuple_1,(9,18,27)
>>> print(tuple_1)
('a', 'Ramana', 36.18)
>>> print(tuple_2)
(('a', 'Ramana', 36.18), (9, 18, 27))
>>>
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.
>>> tuple_1 = ('Python', 'PHP', 39, 55);
>>> tuple_2 = (1, 2, 3, 4, 5, 6, 7 );
>>> print (tuple_1[0])
Python
>>> print (tuple_2[1:5])
(2, 3, 4, 5)
>>>
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.
>>> my_tuple = (1, 4, 2, 3, 6, [7, 5])
>>> my_tuple[5][0] = 8
>>> print(my_tuple)
(1, 4, 2, 3, 6, [8, 5])
>>> my_tuple = ('f','r','e','e','t','i','m','e','l','e','a','r','n')
>>> print(my_tuple)
('f', 'r', 'e', 'e', 't', 'i', 'm', 'e', 'l', 'e', 'a', 'r', 'n')
>>>
We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the *
operator.
Both +
and *
operations result into a new tuple.
>>> # Concatenation
>>> # Output: (1, 2, 3, 4, 5, 6)
>>> print((1, 2, 3) + (4, 5, 6))
(1, 2, 3, 4, 5, 6)
>>> # Repeat
>>> # Output: ('Repeat', 'Repeat', 'Repeat')
>>> print(("Repeat",) * 3)
('Repeat', 'Repeat', 'Repeat')
>>>
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove items from a tuple.
But deleting a tuple entirely is possible using the keyword del.
>>> my_tuple = ('f','r','e','e','t','i','m','e','l','e','a','r','n')
>>> del my_tuple
>>> print(my_tuple)
Traceback (most recent call last):
File "<pyshell#115>", line 1, in <module>
print(my_tuple)
NameError: name 'my_tuple' is not defined
>>>
here are following in-built Type Functions :
Function | Description |
---|---|
min(tuple) | Returns the minimum value from a tuple. |
max(tuple) | Returns the maximum value from the tuple. |
len(tuple) | Gives the length of a tuple |
cmp(tuple1,tuple2) | Compares the two Tuples. |
tuple(sequence) | Converts the sequence into tuple. |