Python Tuple: Easily Understand tuples with 5 examples

What are Tuples in Python?

Among the other compound data types available in Python, the tuple is one of those.

The Tuple is a sequence just like the list, however, tuple data type is immutable. That means once created its values cannot be changed in the program.

A numbered tuple example

A mixed tuple example

Besides, the list uses the square brackets while tuples use parentheses().

Main points about Tuple Python

  • The Tuple items are written as comma separated values in the parentheses i.e. ().

e.g. tuple_name = (1,2,3)

  • A Tuple can store different types of values or items like numbers and strings.

e.g. Py_tuple = (1, 2, ‘Python’, ‘tuple’ )

  • The tuple data type implements the sequence protocol and it is immutable.
  • The Tuples index starts at zero.

A few examples of Tuples

tuple_number = (1,2,3,4,5)

tuple_strings = (‘this’, ‘is’, ‘tuple’, ‘lesson’)

tuple_mixed = (1, ‘this’, 2, ‘is’, 3, ‘tuple’, 4, ‘chapter’)

Example of creating and accessing tuples

In the following example, we will create a tuple with five items and then access this to display the tuple elements.

The Output of the above code:






String tuple example

Following example creates and display a Python tuple of strings elements. We will use a for loop to print the elements of Tuple.

The Output:





Accessing specific item of tuple

In this example, a tuple of mixed items is created. That means it contains numbers and strings. After that we used the print function to display the specific items of the Python tuple as follows:

The Output:

this is tuple chapter

You can see, the specifies items are accessed by using the [], that encloses the index numbers which starts at zero.

Tuple Length Example

The Len() method can be used to get the length of a tuple, as shown in the example below:

The output will be:


Remove tuple example

In this example, a string tuple is created with four elements. After creating and displaying the tuple elements, we used the del method to remove this tuple. As we tried to display that tuple again after using the del method, it generated an error as shown in the example.

The output will be:

(‘this’, ‘is’, ‘tuple’, ‘chapter’)

Traceback (most recent call last):

File “”, line 8, in <module>

print (tuple_Py)

NameError: name ‘tuple_Py’ is not defined

It will generate an error, as tuple has been deleted.

Was this article helpful?

Related Articles

Leave A Comment?