Python tuple is one of python collection which is ordered and unchangeable. Here we will study about python tuple, how they are created, various methods of python tuple with example.Python tuples seems similar to python lists, but they are different.
As we study above ordered and unchangeable feature of tuple:
- ordered feature means elements remains in order format, in which they put into tuple.
- unchangeable feature means elements cannot be modified unlike python list, tuple values can not be modified once it is created.
Python tuples introduction
As we read above Python tuples are ordered collections and they are immutable in nature.
Syntax of Python tuples
basic syntax of Python tuples is
tuple_name=(“element 1″,”element 2″….”element n”)
observation
- here tuple_name is name of tuple variable.
- element 1,element 2 are elements of tuple.
- tuple elements are enclosed with round brackets ().
Example of Python tuples
Let’s understand python tuples with simple example
animals= ("cow", "elephant", "pig") print(animals) print(type(animals))
output
('cow', 'elephant', 'pig') <class 'tuple'>
In above example, animals is name of tuple. we can also check the type of animals by using type function of python.
Operations on python tuples
Now we will perform various operations on python tuples
Access elements of tuple
Here we will see how to access elements of tuple. elements of tuple can be accessed by index number.
animals= ("cow", "elephant", "pig") print(animals[0])
Output
cow
Add elements into tuple
As we read that Python tuples are unchangeable, we can not add elements once tuple is created. it will throw error, if we try to add element in tuple.
animals= ("cow", "elephant", "pig") animals[3]="zebra"
output
TypeError: 'tuple' object does not support item assignment
Remove elements from tuple
elements from python tuple can not be deleted due to its unchangeable feature of Python tuple, but we can delete the whole tuple. del keyword is used to delete the whole tuple.
After apply del command on tuple, if we try to access python tuple, it will throw error
animals= ("cow", "elephant", "pig") del animals print(animals)
output
NameError: name 'animals' is not defined
Update elements in tuple
elements of Python tuple can not be updated once created as Python tuples are immutable in nature. It will throw an error, if try to update its elements.
animals= ("cow", "elephant", "pig") animals[0]="Zebra" print(animals)
Output
TypeError: 'tuple' object does not support item assignment
Python list vs Python tuple
Here we will discuss about Difference between Python tuple and Python list.