Skip to main content
Python-Tuples-Useful-Methods

Python Tuple Example & Methods

This tutorial helps to understand Python tuple with examples. It’s a very common and useful collection types. A tuple is a collection that is ordered and unchangeable.

How To Define Tuple in Python

Python tuples are written with round brackets.

HTML

Access Tuple Items

We can access tuple items by referring to the index number of the tuple item, inside square brackets:

HTML

Negative Indexing

You can also use negative indexing with a tuple. The negative index beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

HTML

The Above code will print the second item of the tuple.

Negative Indexing Into Python Tuple

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.

HTML

The Above code will print the last item of the tuple.

Slicing of Python Tuple

We can specify a range of indexes by specifying where to start and where to end the range. The return value will be a new tuple with the specified items.

We can also pass a negative index to a slice of the tuple.

HTML

The negative range of indexes will generate a new tuple that has index -4 (included) to index -1 (excluded).

Output:

HTML

Change Item Value

As We know, the Tuples are unchangeable, or immutable So we can not change it. But there is a workaround. We can convert the tuple into a list, change the list, and convert the list back into a tuple.

HTML

Output:

HTML

Loop Through a Tuple Item

You can loop through the Tuples items by using a for loop:

HTML

The above code will print all items of tuple:

HTML

Check if Item Exists

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

HTML

The above code will check if “Green” is present in the tuple.

How To Count Length

The len() method is used to determine the length of the tuple.

HTML

Add Items Into The Tuple

You can not add an item to the tuple.

How to Remove An Item From the Python Tuple

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

HTML

How To Join Two Tuple

We can join two or more tuples using + operator.

HTML

Output:

HTML

Leave a Reply

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