Python Tuple
Tuples are immutable,meaning they cannot be changed once they are created.A tuple is a collection which is ordered and unchangeable.
Create a Tuple
We create a tuple by placing elements inside (),separated by commas.
Example
ages = (19, 26, 23) print(ages) Output (19, 26, 23)
Access Tuple Elements
We can access tuple items by referring to the index number,inside square bracket.
Example
fruit = ("apple","banana","cherry") print(fruit[1]) Output banana
Change Tuple Value
Once a tuple is created,we cannot change its values.Tuples are unchangable.
Example
fruit=("apple","banana","cherry") for x in fruit: print(x) Output apple banana cherry
Tuple Length
To determine how many items a tuple has, use the len() function.
Example
fruit = ("apple", "banana", "cherry") print(len(fruit)) Output 3
Remove Items in Tuple
Since tuples are unchangable,so we cannot remove items from it but we can delete the tuple completely.
Example
thistuple = ("apple", "banana", "cherry") del thistuple print(thistuple) Output File "/home/main.py",line 10, in <module> print(thistuple) NameError: name 'thistuple' is not defined
The above output shows that "thistuple" gets deleted completely.
Tuple Constructor
It is possible to use the tuple() constructor to make a tuple.
Example
thistuple = tuple(("apple", "banana", "cherry")) print(thistuple) Output ('apple', 'banana', 'cherry')