Tuple
Tuple is an ordered collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type and they are indexed by integers. The important difference between a list and a tuple that tuples are immutable. Its represented by tuple class.
Creating a tuple
In Python tuples are created by placing sequence of values separated by 'comma' with or without the use of parentheses. Tuple can contain any number of elements and of any data type like strings, integers, list etc.
Note : Creation of Python tuple without the use of parentheses is known as "Tuple Packing".
A tuple can be defined as follows :-
- Tuple1 = (101, "Peter", 22)
- Tuple2 = ("Apple", "Banana", "Orange")
- Tuple3 = 10,20,30,40,50
- print(type(Tuple1))
- print(type(Tuple2))
- print(type(Tuple3))
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Example
# creating an empty tuple
tuple=()
print(tuple)
# creating a tuple with the use of strings
tuple=('btech','second','year')
print(tuple)
# creating a tuple with the use of list
list=[1,2,3,4,5]
print(tuple(list))
#creating a tuple with the use of built-in function
tuple=tuple('btech')
print(tuple)
Output
Accessing element of a tuple
In order to access tuple item refer to the index number. use the index operator [] to access an item in a tuple. The index must be an integer.
Example
Output
Note : In Python, deletion or updation of a tuple is not allowed. This will cause an error because updating or deleting from a tuple is not supported. This is because tuples are immutable, hence element of a tuple cannot be changed once it has been assigned. Only new tuples can be reassigned to the same name.
Excellent content
ReplyDelete