Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. One major feature of tuples is that they are immutable like strings i.e. you cannot modify tuples.

1. CREATE A TUPLE IN PYTHON

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

OUTPUT:

CREATE TUPLE IN PYTHON
OUTPUT – CREATE TUPLE IN PYTHON

2. ACCESS TUPLE ITEMS IN PYTHON

You can access tuple items by referring to the index number, inside square brackets.

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

OUTPUT:

ACCESS TUPLE IN PYTHON
OUTPUT – ACCESS TUPLE IN PYTHON

3. CHANGE TUPLE VALUES IN PYTHON

Once a tuple is created, you cannot change its values. Tuples are unchangeable.

4. ITERATE (loop) THROUGH A TUPLE IN PYTHON

You can loop through the tuple items by using for loop.

thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)

OUTPUT:

ITERATE THROUGH TUPLE IN PYTHON
OUTPUT – ITERATE THROUGH TUPLE IN PYTHON

5. CHECK IF ITEM EXISTS IN PYTHON

To determine if a specified item is present in a tuple use the in keyword.

thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
  print("Yes, 'apple' is in the fruits tuple")

OUTPUT:

CHECK ITEM IN TUPLE IN PYTHON
OUTPUT – CHECK ITEM IN TUPLE IN PYTHON

6. TUPLE LENGTH IN PYTHON

To determine how many items a tuple has, use the len() method.

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

OUTPUT:

TUPLE LENGTH IN PYTHON
OUTPUT – TUPLE LENGTH IN PYTHON

7. ADD ITEMS IN PYTHON

Once a tuple is created, you cannot add items to it. Tuples are unchangeable.

8. REMOVE ITEMS IN PYTHON/ DELETE TUPLE IN PYTHON

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely.

thistuple = ("apple", "banana", "cherry")
del thistuple
#this will raise an error because the tuple no longer exists
print(thistuple)

OUTPUT:

REMOVE ITEM IN PYTHON
OUTPUT – REMOVE ITEM IN PYTHON

One thought on “Tuple”

  1. *Oh my goodness! an amazing article dude. Thank you However I am experiencing issue with ur rss . Don?t know why Unable to subscribe to it. Is there anyone getting identical rss problem? Anyone who knows kindly respond. Thnkx

Leave a Reply

Your email address will not be published. Required fields are marked *