Python Tuple

The Python Tuple is almost similar to a List except that these are immutable, and Lists are mutable. It means Once we declare the Python Tuple, we cannot change the values or items inside it, something like Constant keyword in other programming languages.

What is a tuple in Python?

A Python Tuple is a sequence of multiple values in an ordered sequence. Tuples are declared using Open and Closed Parenthesis ( ). Unlike Strings, Python Tuple allows us to store different types of data such as integer, float, string, etc.

How to Declare Python Tuple?

To declare an empty Tuple in Python that contains no values, use TupleName = ().

Like any other collection, we have to declare the elements where each item is separated by commas. Even to declare this object with one item, we have to specify a comma after the item.

For instance: TupleName = (245,). Forgot to add a comma, then it is an integer type (Not a Tuple). The following are the list of possible ways to declare a String, Mixed, Nested and List Tuples in Python.

StringTup = (‘apple’, ‘Orange’, ‘Grape’, ‘Mango’) is a string tuple that contains four string values.

MixedTup = (‘apple’, 2, 3.50, ‘Mango’) is a mixed one that contains one integer, one float, and two integer values.

NestedTup = (‘Gateway’, ‘Tutorial’, (1, 2, 3) ) is an example of one inside another (Nested).

ListTup = (‘Py’, ‘Tutorial’, [1, 2, 3] ) is an example of List inside it.

How to access Python Tuple items?

We can access the Python Tuple items using indexes. Using the index, we can access each item present in it separately. Index value starts at 0 and ends at n-1, where n is the size. Using the Negative numbers as an index, it starts looking for elements from right to left.

For instance, if a class store 5 elements, then the index starts at 0 and ends with 4. To access the first value, use TupName[0] and to access the fifth value, use TupName[4]. Let us see the integer data type example for better understanding:

x = (1, 2, 3, 4, 5, 6, 7, 8, 9)

# Positive Indexing
print(x[0])
print(x[4])
print(x[8])
print('=======\n')

# Negative Indexing
print(x[-2])
print(x[-4])
print(x[-8])
print('=======\n')

MixedTup = ((1, 2, 3), [4, 5, 6], 'Learn')
print(MixedTup[0][0])
print(MixedTup[1][0])
print(MixedTup[2][0])
print(MixedTup[2][4])
1
5
9
=======

8
6
2
=======

1
4
L
n

Iterating Python Tuple

The For Loop is the most popular way to traverse the elements. The following statement helps to iterate the object and print the items inside the Fruits.

Fruits = ('Apple', 'Orange', 'Grape', 'Banana', 'Strawberry','Cherry', 'Kiwi')
for Fruit in Fruits:
    print(Fruit)
Iterating Python Tuple

Arithmetic Operations

In this example, we show the use of Arithmetic Operators on Python Tuple to perform arithmetic operations.

X = (1, 2, 3)
Y = (4, 5, 6)
Sum = X + Y
print(Sum)

# Using * Operator
Z = X * 3
print(Z)

Performing the Arithmetic Operations output. Refer to create it using numbers example.

(1, 2, 3, 4, 5, 6)
(1, 2, 3, 1, 2, 3, 1, 2, 3)

From the above output, you can observe that

  • + operator is concatenating
  • * operator is repeating for a given number of times. Here it is three times

Python Tuple slice

In python Tuple Slice syntax, the first integer value is the index position where the slicing starts, and the second one is the index position where the slicing end.

The slicing goes up to second integer value but not include the value at this index position. For instance, if we specify tuple_exmp[1:4], then slicing starts at index position 1 and ends at position 3 (not 4).

x = (1, 2, 3, 4, 5, 6, 7, 8, 9)

# Slicing using two indexes
a = x[2:6] 
print(a)

# Slicing using First
b = x[:6] 
print(b)

# Using Second
c = x[2:] 
print(c)

# Without using two
d = x[:] 
print(d)

# Slice using Negative
e = x[-3:] 
print(e)

# Slice using Negative
f = x[:-2] 
print(f)
(3, 4, 5, 6)
(1, 2, 3, 4, 5, 6)
(3, 4, 5, 6, 7, 8, 9)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
(7, 8, 9)
(1, 2, 3, 4, 5, 6, 7)

Slicing analysis

  • If no first index, then Python Slicing starts from the beginning
  • If the second index not provided, Slicing starts from the first index and continue to the last
  • Using the Negative numbers as the index, Slicing starts from right to left.

Altering Tuple items

It won’t allow altering the Python tuple items inside it. Let’s see what happens when we do that?

Removing Python Tuple Data

Analysis: Within the First statement, We assigned a new value at index position two. Since it is immutable, the output is throwing a Type Error. Within the Second statement, We assigned a new value to this inside another at index position one.

Although it is a Nested Python tuple, the output is throwing a Type Error because it is immutable. In the Third statement, We assigned a new value at position [1][1], and that is List inside it. Since List is mutable, we successfully changed the value from 5 to 14.

Python Tuple Methods

It provides the following methods. The Python tuple() method helps to convert the String or Lists into Tuple.

The min function helps us to find the Smallest or minimum item and the max function finds the Largest item or largest item.

The Len method finds or calculates the Length or Number of items and the sorted method helps to sort the elements in ascending order. The index function returns the index position of a specified value.

The sum function calculates the sum of all items inside the given one. And the count function counts the total number of times the specified value repeated.

In the below program, we are applying all the Python Tuple methods. It might help to see all the functions.

FruitsTP = ('Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry')
tp = (9, 4, -5, 0, 22, -1, 2, 14)

#Finding Sum of all item in a  using Sum() Method
print('Sum of all items in a tp  = ', sum(tp))

#Calculating Length of a  using len() Method
print('Length of a FruitsTP  = ', len(FruitsTP))
print('Length of a tp  = ', len(tp))

#Finding Minimum item in a  using min() Method
print('Minimum item in a FruitsTP  = ', min(FruitsTP))
print('Minimum item in a tp  = ', min(tp))

#Finding Maximum item in a  using max() Method
print('Maximum item in a FruitsTP  = ', max(FruitsTP))
print('Maximum item in a tp  = ', max(tp))

# Using Sorted() Method
print('After Sorting FruitsTP  = ', sorted(FruitsTP))
print('After Sorting tp  = ', sorted(tp))

# Index position of an item in a  using index() Method
print('The Index position of Banana = ', FruitsTP.index('Banana'))
print('The Index position of -1 = ', tp.index(-1))

# Counting items in a  using count() Method
tp2 = (9, 4, 1, 4, 9, -1, 2, 4)
print('Number of Times 4 is repeated = ', tp2.count(4))
print('Number of Times 9 is repeated = ', tp2.count(9))

# Converting List
tp3 = [1, 2, 3, 4, 5]
print(tuple(tp3))
Sum of all items in a tp  =  45
Length of a FruitsTP  =  6
Length of a tp  =  8
Minimum item in a FruitsTP  =  Apple
Minimum item in a tp  =  -5
Maximum item in a FruitsTP  =  Orange
Maximum item in a tp  =  22
After Sorting FruitsTP  =  ['Apple', 'Banana', 'Blackberry', 'Grape', 'Kiwi', 'Orange']
After Sorting tp  =  [-5, -1, 0, 2, 4, 9, 14, 22]
The Index position of Banana =  2
The Index position of -1 =  5
Number of Times 4 is repeated =  3
Number of Times 9 is repeated =  2
(1, 2, 3, 4, 5)