Tuples in Python
Tuples
Basically Tuples in Python are very similar to Lists, but, Tuples are immutable which means that they can not be modified/changed. We generally use Tuples to make sure the values are not changed like, dates, Year, and days of the week or dates on a Calendar.
Creating a Tuple:
>>> my_t1=(1,2,3)
>>> my_t2=('one','two','three')
>>> my_t1
(1, 2, 3)
>>> my_t2
('one', 'two', 'three')
-- check the length of tupple:
>>> len(my_t1)
3
>>> len(my_t2)
3
-- Tuples can have mixed objects as like Lists.
>>> my_t3=(1,'two',3,'four')
>>> my_t3
(1, 'two', 3, 'four')
-- indexing with tuples
>>> my_t3=(1,'two',3,'four')
>>> my_t3[2]
3
Immutable Tuples
We can not modify the value. Here is the example:
>>> my_t3=(1,'two',3,'four')
>>> my_t3[2]=4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
-- can not append/add too
>>> my_t3=(1,'two',3,'four')
>>> my_t3.append('five')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
Comments
Post a Comment