# Tuple Operations in Python | Example Program

In this tutorial, we will perform the most important tuple operations in Python with the help of important example programs.

## Concatenating Tuples in Python

Like in lists, we can use + operator to combine or concatenate two tuples together. This process is called concatenation of tuples.

When we combine two tuples, it forms new tuple because tuples are immutable in nature. So, let us take an example program to perform concatenation operation.

Example 1:

```# Python program to combine two tuples.
# Creating two numeric tuples.
tuple1 = (2, 4, 6, 8)
tuple2 = (10, 12, 14, 16)

# Combining both tuples using + operator.
new_tuple = tuple1 + tuple2

# Displaying new tuple elements.
print("New tuple elements: ", new_tuple)
```
```Output:
New tuple elements:  (2, 4, 6, 8, 10, 12, 14, 16)
```

In this example, we have created two tuples named tuple1 and tuple2 of integer type. Then, we have combined both tuples using + operator to form new tuple. The new tuple contains all elements of added tuples.

## Tuple Multiplication in Python

We can use the multiplication operator * to repeat a sequence of elements in the tuple for a given number of times. In this case, a new tuple also formed. Let’s take an example to perform this operation.

Example 2:

```# Python program to repeat a sequence of elements in a tuple.
my_tuple = (2, 4, 6)

# Repeating a sequence of elements two times in tuple using * operator.
new_tuple = my_tuple * 2

# Displaying new tuple elements.
print("New tuple elements: ", new_tuple)
```
```Output:
New tuple elements:  (2, 4, 6, 2, 4, 6)
```

In this example, we have created a tuple and repeated it two times using multiplication operator * to form new tuple. Then, we have displayed elements of new tuple on the console.

## Delete a Tuple Element in Python

However, it is not possible to update or modify in the tuple. But, we can delete or remove tuple elements using a keyword del. Let’s take an example to delete operation.

Example 3:

```# Python program to delete a tuple.
my_tuple = ("A", "B", "C", "D")
print("Before deleting, tuple elements: ", my_tuple)

# Deleting a tuple.
del my_tuple
print("After deleting, tuple elements: ", my_tuple)
```
```Output:
Before deleting, tuple elements:  ('A', 'B', 'C', 'D')
NameError: name 'my_tuple' is not defined
```

As you can see in the output we got an error because we are trying to print its elements which are not existing anymore after deleting tuple.

## Find Length of Tuple in Python

Python provides a built-in len() function that returns length of tuple. It is equivalent to the number of its elements in a tuple. Let’s take an example to perform this operation.

Example 4:

```# Python program to find length of a tuple.
my_tuple = ("A", "B", "C", "D", "E")

# Determine length of tuple using len() function.
length_of_tupple = len(my_tuple)
print("Length of tuple: ", length_of_tupple)
```
```Output:
Length of tuple:  5
```

## How to Iterate Tuple in Python

Iterating over a tuple is one of the most common operations in Python. To iterate over a tuple, we can use for or while iterative statements to extract the individual element from the tuple. So, let’s discuss each one by one.

### 1. Using for loop:

The for loop is an iterative control statement that iterates over tuple from the starting index till the end index. It creates a definite loop to iterate for each element of the tuple. Look at the following program showing how to iterate tuple using for loop.

Example 5:

```# Python program to iterate over a tuple.
my_tuple = ("A", "B", "C", "D", "E")

# Iterating over tuple.
print("Elements of tuple: ")
for x in my_tuple:
print(x)
```
```Output:
Elements of tuple:
A
B
C
D
E
```

In this example, the for loop takes each individual element from a tuple at every iteration and assigns it to the variable x. Then, we have displayed the extracted element in the body of the loop.

The main problem in this program is that if we want to get the index of every element, we cannot extract it because only elements of tuple can be extracted. We can resolve this problem in the following program.

Example 6:

```# Python program to iterate over a tuple.
my_tuple = ("A", "B", "C", "D", "E")

# Iterating over tuple.
print("Elements of tuple with index: ")
for x in range(len(my_tuple)):
print("Element: ", my_tuple[x], "Index: ", x)
```
```Output:
Elements of tuple with index:
Element:  A Index:  0
Element:  B Index:  1
Element:  C Index:  2
Element:  D Index:  3
Element:  E Index:  4
```

In this example, we have used the range() function to iterate over the tuple. The range() function produces the index values ranging from 0 to length of the tuple and assign to x.

Inside the loop body, we simply extract the element stored in a particular index by my_tuple[x] and extract the index by variable x. In both examples, x works as the loop control variable.

### 2. Using while loop:

The while loop is an iterative control statement we can use it to iterate over a tuple. It iterates till the condition specified in the while statement evaluates to true. Let’s take an example based on it.

Example 7:

```# Python program to iterate over a tuple using while loop.
my_tuple = ("AA", "BB", "CC", "DD", "EE")

# Iterating over tuple.
print("Elements of tuple: ")
index = 0 # Initialization
while(index < len(my_tuple)):
y = my_tuple[index]
print("Element: ", y, "Index: ", index)
index += 1
```
```Output:
Elements of tuple:
Element:  AA Index:  0
Element:  BB Index:  1
Element:  CC Index:  2
Element:  DD Index:  3
Element:  EE Index:  4
```

Remember that you need to take care of initialization and updation of the loop control variable while using while loop statement. If you forget to write initialization and updation of the loop control variable or change their order, then it leads to a change in the result provided by the program.

## Search Element from a Tuple

We can also use it to find a specific element from the list. Let’s take an example to perform search operation.

Example 8:

```# Python program to search an element from a tuple using while loop.
my_tuple = ("AA", "BB", "CC", "DD", "EE")
x = input("Enter element to be searched: ")
index = 0
while(index < len(my_tuple)):
if x == my_tuple[index]:
print("Element found at position: ", index + 1)
break
index += 1
else:
```
```Output:
Enter element to be searched: CC
Element found at position:  3
```

In this example, we have used while loop to iterate over a tuple, starting from 0 to the length of tuple. The while loop will search the element in the tuple at every iteration.

If the element is found at a specific index position, it prints the position of element in the tuple. Otherwise, it continues to traverse the last element in the tuple. If the element is not found in the tuple, it prints the message from the body of else statement.

## Check Existence of Element in Tuple

We can check for the presence of an element in a tuple using in and not in membership operators. It always returns a boolean value either True or False. Let’s take an example to check this operation.

Example 9:

```# Python program to check the existence of elements in tuple.
my_tuple = ("AAA", "BBB", "CCC", "DDD", "EEE")

# Checking the existence of elements in tuple using in operator.
result1 = "BBB" in my_tuple
print(result1)
result2 = "FFF" in my_tuple
print(result2)

# Checking the existence of elements in tuple using not in operator.
result3 = "AAA" not in my_tuple
print(result3)
result4 = "PPP" not in my_tuple
print(result4)
```
```Output:
True
False
False
True
```

## Important Programs based on Python Tuple Operations

Example 10:

Let us write a Python program to unpack a tuple in several variables.

```my_tuple = (82, 84, 86)
print(my_tuple)

# Unpacking elements of tuple into variables n1, n2, and n3.
n1, n2, n3 = my_tuple
print("n1: ", n1)
print("n2: ", n2)
print("n3: ", n3)

sum = n1 + n2 + n3
print(sum)
```
```Output:
(82, 84, 86)
n1:  82
n2:  84
n3:  86
252
```

Example 11:

Let’s write a Python program to determine a repeated element in the tuples.

```my_tuple = (2, 3, 4, 5, 2, 2, 3, 5, 4, 5)
print(my_tuple)

# Count the repeated elements in the tuple.
count1 = my_tuple.count(2)
print("No of occurrences of element 2: ", count1)

count2 = my_tuple.count(3)
print("No of occurrences of element 3: ", count2)
```
```Output:
(2, 3, 4, 5, 2, 2, 3, 5, 4, 5)
No of occurrences of element 2:  3
No of occurrences of element 3:  2
```

Example 12:

Let’s write a Python program to sort a tuple elements in a ascending order.

```my_tuple = (2, 3, 5, 1, 6, 8, 10, 4, 7)
print(my_tuple)

# Sorting tuple in ascending order.
sort = sorted(my_tuple)
print("Element in ascending order: ", sort)
```
```Output:
(2, 3, 5, 1, 6, 8, 10, 4, 7)
Element in ascending order:  [1, 2, 3, 4, 5, 6, 7, 8, 10]
```

Example 13:

Let us write a program to convert a tuple into a dictionary.

```my_tuple = ((1, "Rashmi"), (2, "Deep"), (3, "Amit"))

# Converting a tuple into dictionary.
print(dict((x, y) for x, y in my_tuple))
```
```Output:
{1: 'Rashmi', 2: 'Deep', 3: 'Amit'}
```

In this example, we have created nesting tuples within a tuple, wherein each nested tuple element contains two elements in it. Then, we have converted it into a dictionary by passing tuple name to the dict() function. When the tuple gets converted into a dictionary, the first element becomes key and the second element becomes its value.

Example 14:

Let us write a program in Python to convert a list into a tuple.

```my_list = ["John", "Amit", "Deep", "Rash"]
print(my_list)

# Converting a list into tuple.
my_tuple = tuple(my_list)
print(my_tuple)
```
```Output:
['John', 'Amit', 'Deep', 'Rash']
('John', 'Amit', 'Deep', 'Rash')
```

In this example, we have created a list named my_list of string type. Then, we have converted it into a tuple by passing tuple name to the tuple() function. When the list gets converted into a tuple, we have printed the tuple elements.

Example 15:

Let us write a program in Python to convert a tuple into a list.

```my_tuple = ("John", "Amit", "Deep", "Rash")
print(my_tuple)

# Converting a tuple into list.
my_list = list(my_tuple)
print(my_list)
```
```Output:
('John', 'Amit', 'Deep', 'Rash')
['John', 'Amit', 'Deep', 'Rash']
```

In this example, we have created a tuple, containing all the elements of string type. Then, we have converted it into a list by passing tuple name to the list() function. When the tuple gets converted to a list, then we have stored it into a variable my_list and printed it on the console.

In this tutorial, we have discussed the most important tuple operations in Python with the help of various example programs. Hope that you will have understood the basic tuple operations and practiced all example programs. In the next tutorial, we will understand the basic differences between list and tuple in Python.