Python Tuples

In Python, a tuple is a collection which is ordered and immutable. That means we cannot add or remove items from the tuple.

We create tuples using parenthesis () and at least one comma ( , ).

Tuples can be indexed and sliced just like lists, except that the result of the slice will also be a tuple.

How to Create a Tuple

colorsTuple = ("red", "green", "blue")
print(colorsTuple)

Output:

('red', 'green', 'blue')

Creating a Tuple With Only One Item

Tuples require at least one comma, so to create a tuple with only one item, you have add a comma after the item. For example:

colorsTuple = ("red",)

How to Access Items of a Tuple

We can access tuple items by referring to the index number:

colorsTuple = ("red", "green", "blue")
print(colorsTuple[2])

Output:

blue

Accessing a Range of Items (Slicing)

We can specify a range of items from a tuple by specifying the starting index and the end index. We use the : operator.

colorsTuple = ("red", "green", "blue", "yellow", "orange", "white")
print(colorsTuple[1:4])

Output:

('green', 'blue', 'yellow')

Negative Indexing

We can access the items on the tuple from the end by specifying a negative index value. For example -1 means the last item and -2 means the second last item.

colorsTuple = ("red", "green", "blue", "yellow", "orange", "white")
print(colorsTuple[-2])

Output:

orange

How to Loop Through a Tuple

We can loop through a tuple using the for loop.

colorsTuple = ("red", "green", "blue", "orange")
for c in colorsTuple:
    print(c)

Output:

red
green
blue
orange

How to Delete a Tuple

To delete a tuple completely, use the del keyword

colorsTuple = ("red", "green", "blue", "orange")
del colorsTuple
print(colorsTuple)

Output

Traceback (most recent call last):
  File "pythonTuples.py", line 98, in <module>
    print(colorsTuple)
NameError: name 'colorsTuple' is not defined

How to Get the Length of a Tuple

You can get the tuple length by calling the len() function, e.g.:

colorsTuple = ("red", "green", "blue", "orange")
print(len(colorsTuple))

Output:

4

Count Number of Specified Items

We can use the count() function on the tuples to get the number of occurances of a specified item in the tuple. For example:

colorsTuple = ("red", "green", "blue", "orange", "red")
print(colorsTuple.count("red"))

Output:

2

How to Join Two Tuples Together

The easiest way to join two tuples together is to use the + operator. For example:

colorsTuple = ("red", "green", "blue", "orange")
numbersTuple = (1, 2, 3, 4)

numbersAndColors = colorsTuple + numbersTuple
print(numbersAndColors)

Output:

('red', 'green', 'blue', 'orange', 1, 2, 3, 4)