A Tuple can be defined as a ordered collection of objects which are immutable.
Tuples are also sequences just like lists.But the main difference between these 2 is lists are mutable(can be changed) but tuples are immutable(cannot be changed) unlike lists.
Tuples uses parentheses().
tup1=('Computer','Laptop',30,70);
tup2=(1,2,3,4,5);
tup3=(50,); # a single valued tuple also contain comma(,)
To create an empty tuple:
tup1=();
Like strings, tuple index also starts from 0 and they can be sliced,concatenated and so on.
To access the tuple values,we use the square brackets[ ] for slicing along with the index or indices to obtain value available at the index.It is similar to string.
tup1=('Computer','Laptop',30,70);
tup2=(1,2,3,4,5);
print(tup1[0])
print(tup2[3])
Output:
Computer
4
Slicing can also be used in tuples as mentioned above.Let's take an example:
tup3=(12,23,34,45,56,67,78,89);
print(tup3[3:7])
Output:
[45,56,67,78]
As said earlier,tuples are immutable that means it cannot be changed or updated.You can see below what happens if we try to change the tuple variable.
Deletion of tuple elements is not possible because tuples are immutable.However, the entire tuple can be deleted by keyword del.It deletes the entire tuple.
tup1=('Computer','Laptop',30,70);
print(tup1)
del tup1
The above code will remove the entire tuple.
Code:
tup3=(12,23,34,45,56,67,78,89);
print(len(tup3))
Output:
8
This function will return the item with maximum value from the tuple.
Code:
tup3=(12,23,34,45,56,67,78,89);
print(max(tup3))
Output:
89
This function will return the item with minimum value from the tuple.
Code:
tup3=(12,23,34,45,56,67,78,89);
print(min(tup3))
Output:
12
This function is used to convert a list into a tuple.