Tuples in Python

A tuple is a python datatype similar to lists but the items of the tuple cannot be changed. Tuples contain a sequence of elements called items which are indexed, ordered and immutable.

The items in a tuple are surrounded by parentheses and separated by a comma(,).

Since the items of a tuple cannot be modified, it is used to group the data in a single unit that does not require any changes in future.

This article will tell you about:

How to create a Tuple in Python?

To create a tuple, the items are placed between a pair of parentheses.

Syntax:
tuple_name = (item_1, item_2, item_3, . . .)

Example:

prices = ( 399, 449, 999, 879, 559)
print("prices = ", prices)

Output:

prices = (399, 449, 999, 879, 559)

You can also use the tuple constructor to create a tuple.

Syntax:
tuple_name = tuple((item_1, item_2, item_3, . . . ))

Example:

prices = tuple(( 399, 449, 999, 879, 559))
print("prices = ", prices)

Output:

prices = (399, 449, 999, 879, 559)

It is a good programming practice use parentheses while creating a tuple but it is not mandatory. A tuple can also be defined without parentheses.
Syntax: tuple_name = item_1, item_2, item_3 . .
A comma must a be used to separate the items in a tuple. Even if a tuple contains a single item, it must be followed by a comma.

Indexing of the tuple items

Tuple is an indexed sequence, where the index of the first item is zero. The indexing proceeds toward the right in the tuple.

Tuples also have negative indexing in which the index of the last item is -1. The indexing proceeds towards the left in the tuple.

How to access the items in the tuple?

The index of items is the medium to access the value of the item in the tuple.

Syntax:
tuple_name[index]

Example:

prices = ( 399, 449, 999, 879, 559)
print("prices = ", prices)
print("Item at index 0 = ", prices[0])
print("Item at index 4 = ", prices[4])
print("Item at index -4 = ",prices[-4])

Output:

prices = (399, 449, 999, 879, 559)
Item at index 0 = 399
Item at index 4 = 559
Item at index -4 = 449

Slicing in Python Tuple

Slicing allows you to access more than one item at a time. You can access a part of the tuple instead of the full tuple. For slicing, you need to specify the beginning and end of the slice.

Syntax:
tuple_name[a:b]
The value from index a to index b-1 will be accessed.

or
tuple_name[a:]
The value from index a to the end of the tuple will be accessed.

or
tuple_name[:b]
The value from the index 0 to index b-1 will be accessed.

Example:

prices = ( 399, 449, 999, 879, 559)
print("prices = ", prices)
print("prices[1:4] = ", prices[1:4])
print("prices[1:] = ", prices[1:])
print("prices[:4] = ",prices[:4])

Output:

prices = (399, 449, 999, 879, 559)
prices[1:4] = (449, 999, 879)
prices[1:] = (449, 999, 879, 559)
prices[:4] = (399, 449, 999, 879)

How to change the items of a tuple in Python?

It is not poosible to change the items of the tuple once created. If you try to modify the values of the items, you will face an error.
Check out the example below:

prices = (399, 449, 999, 879, 559)
print("prices = ", prices)
prices[1] = 759 #changing the value at index 1

Output:

TypeError: 'tuple' object does not support item assignment

How to delete a Tuple in Python?

del keyword is used to delete the entire tuple from the memory.

Syntax:
del tuple_name

Example:

prices = (399, 449, 999, 879, 559)
del prices #deleting the tuple
print(prices)

Output:

NameError: name 'prices' is not defined

Explanation:
You can clearly see that the program generates an error saying name 'prices' is not defined. This is because the tuple is already deleted.

For Loop with Python Tuples

You can use for loop to visit every item one by one in a tuple. This is known as iterating.

Syntax:
for x in tuple_name:
     body of the loop

Example:

prices = (399, 449, 999, 879, 559)
print("prices =", prices)
for x in prices:
     print("Item",prices.index(x)," =", x)

Output:

prices = (399, 449, 999, 879, 559)
Item 0 = 399
Item 1 = 449
Item 2 = 999
Item 3 = 879
Item 4 = 559

Explanation:
In the above program, a for loop is used to print the index and the value of the items one by one. The index() method is used to fetch the index of the items.

How to calculate the length of the tuple?

Python provides the len() function to find out the length i.e the number of items inside the tuple. The number of items is counted by this function and it returns the count in the form of an integer.
You just need to give the name of the tuple as the argument to the function.

Syntax:
len(tuple_name)

Example:

prices = (399, 449, 999, 879, 559)
print("Length of the tuple prices =", len(prices))

Output:

Length of the tuple prices = 5

max() & min() function with Tuples

max() and min() are built-in functions in python which can find out the maximum or minimum value among all the items in a tuple. These functions work only with the tuples which have number or floating-point values, not with strings.

Name of the tuple is passed as the parameter to the function.

Syntax:
max(tuple_name)
min(tuple_name)

Example:

marks = (97,82,68,77,85) #creating a tuple.
print("Marks of 5 students:")
for x in marks: #displaying the items of the tuple one by one.
    print(x)
highest = max(marks) #fetching the maximum value from the tuple. 
lowest = min(marks) #fetching the minimum value from the tuple.
print("Highest marks=", highest)
print("Lowest marks=", lowest)


Output:

Marks of 5 students:
97
82
68
77
85
Highest marks= 97
Lowest marks= 68

Tuple Methods in Python

Since tuples are immutable, there are only a couple of methods are available.

1. count()

Python provides the count() method to count the number of times the given item appears in the tuples
Argument to be passed: Value of the item

Syntax:
tuple_name.count(value)

Example:

attendance = ('a','p','a','a','p','a','p')
print("Present = ", attendance.count('p'))
print("Absent = ", attendance.count('a'))

Output:

Present = 3
Absent = 4

2.index()

index() method is used to find out the index of an item. It returns the positive index of the item.
Argument to be passed: Value of the item

Syntax:
tuple_name.index(value)

Example:

prices = (399, 449, 999, 879, 559)
print("prices =", prices)
print("Index of item 399 =", prices.index(399))
print("Index of item 999 =", prices.index(999))
print("Index of item 559 =", prices.index(559))

Output:

prices = (399, 449, 999, 879, 559)
Index of item 399 = 0
Index of item 999 = 2
Index of item 559 = 4

Concatenation and Multiplication of Python Tuples

Although tuples are immutable, they can be concatenated with other tuples or can be replicated using + and * operators respectively.

  • Concatenation: The + operators simple concatenates the items of two or more tuples.

    Syntax:
    tuple_name1 + tuple_name2 + tuple_name3 + . . .

    Example:

    color = ('red','green','yellow','blue')
    days = ('monday','tuesday','wednesday','thursday')
    new = color + days
    print("color =",color)
    print("days =",days)
    print("color + days =",new)

    Output:

    color = ('red', 'green', 'yellow')
    days = ('monday', 'tuesday', 'wednesday')
    color + days = ('red', 'green', 'yellow', 'monday', 'tuesday', 'wednesday')
  • Multiplication: The * operator is used to replicate a tuple for the desired number of times.

    Syntax:
    tuple_name * n
    n is an integer. The tuple is repeated n times.

    Example:

    color = ('red','green','yellow')
    print("color =",color)
    print("color * 3 =", color * 3)

    Output:

    color = ('red', 'green', 'yellow')
    color * 3 = ('red', 'green', 'yellow', 'red', 'green', 'yellow', 'red', 'green', 'yellow')