Python Tuples

Python Tuples
A tuple in python is a collection of data which is ordered and unchangable. In Python programming you can create tuples with the round brackets.

thistuple = ("apple", "banana", "cherry")

print(thistuple)


Access Tuple Items
You can access the items of a tuple by just reffering to the index number of the element inside the square braackets:

thistuple = ("apple", "banana", "cherry")

print(thistuple[1])



Change Tuple Values
Once you have created a tuple then you cannot change the values of the tuple as the tuples are unchangable.

Loop Through a Tuple
Using the for loop you can loop through a tuple. For better understanding let us consider the following example:

thistuple = ("apple", "banana", "cherry")

for x in thistuple:

     print(x)


Check if Item Exists
If you want to check that a specific element is present in a tuple then you can use the in keyword. For example let us consider the following example:

thistuple = ("apple", "banana", "cherry")

thistuple = ("apple", "banana", "cherry")

if "apple" in thistuple:

     print("Yes, 'apple' is in the fruits tuple")


Tuple Length
If you want to find the length of a tuple then you can use the len() method in order to find that.

thistuple = ("apple", "banana", "cherry")

print(len(thistuple))


Add Items
As we know that tuples are unchangable, so if once a tuple is been created then you cannot add the elements in the tuple.

Remove Items
As we know that tuples are unchangable, so the elements cannot be removed from the tuple, but the entire tuple can be deleted.

The tuple() Constructor
If you want to create a tuple then you can use the tuple() constructor directly and it will generate a tuple for you for the elements that you will give in this function. For better understanding let us consider the following example.

thistuple = tuple(("apple", "banana", "cherry"))

print(thistuple)