Table of Contents

Tuple Data Structure

1. Tuple is same as List except that it is immutable.

2. If our data is fixed and never changes then we should go for Tuple.

3. Insertion Order is preserved

4. Duplicates are allowed

5. Heterogeneous objects are allowed.

6. We can preserve insertion order and we can differentiate duplicate objects by using

index. Hence index will play very important role in Tuple also.

Tuple support both +ve and -ve index. +ve index means forward direction (from left to right) and -ve index means backward direction (from right to left)

7. We can represent Tuple elements within Parenthesis and with comma separator.

Ex: t=10,20,30,40

print(t)

Output

(10, 20, 30, 40)

**Tuple
creation:**

t=10,20,30

t=(10,20,30)

creation of multi values tuples & parenthesis are optional

By using tuple() function:

1. list=[10,20,30]

2. t=tuple(list)

3. print(t)

4. t=tuple(range(10,20,2))

5. print(t)

**How
can we access elements of tuple?**

We can access either by index or by slice operator

**1. By using index:**

1. t=(10,20,30,40,50,60)

2. print(t[0]) #10

3. print(t[-1]) #60

4. print(t[100]) IndexError: tuple index out of range

2. By using slice operator:

t=(10,20,30,40,50,60)

print(t[2:5])

(30, 40, 50)

**Why
is Tuple immutability?**

Once we creates tuple, we cannot change its content.

Hence tuple objects are immutable.

Eg:

t=(10,20,30,40)

t[1]=70 TypeError: ‘tuple’ object does not support item assignment

**Explain
some of Mathematical operators for tuple:**

We can apply + and * operators for tuple

1. **Concatenation Operator(+):**

1. t1=(10,20,30)

2. t2=(40,50,60)

3. t3=t1+t2

4. print(t3) # (10,20,30,40,50,60)

2. **Multiplication operator or repetition
operator(*)**

1. t1=(10,20,30)

2. t2=t1*3

3. print(t2) #(10,20,30,10,20,30,10,20,30)

**What
are the important functions of Tuple?**

**1. len()**

To return number of elements present in the tuple

Eg:

t=(10,20,30,40)

print(len(t)) #4

**2. count()**

To return number of occurrences of given element in the tuple

Eg:

t=(10,20,10,10,20)

print(t.count(10)) #3

**3. index()**

returns index of first occurrence of the given element.

If the specified element is not available then we will get ValueError.

Eg:

t=(10,20,10,10,20)

print(t.index(10)) #0

print(t.index(30)) ValueError: tuple.index(x): x not in tuple

**4. sorted()**

To sort elements based on default natural sorting order

1. t=(40,10,30,20)

2. t1=sorted(t)

3. print(t1)

4. print(t)

5.

6. Output

7. [10, 20, 30, 40]

8. (40, 10, 30, 20)

We can sort according to reverse of default natural sorting order as follows

t1=sorted(t,reverse=True)

print(t1) [40, 30, 20, 10]

###### 5. min() and max() functions:

These functions return min and max values according to default natural sorting order.

Eg:

1. t=(40,10,30,20)

2. print(min(t)) #10

3. print(max(t)) #40

###### 6. cmp():

It compares the elements of both tuples.

If both tuples are equal then returns 0

If the first tuple is less than second tuple then it returns -1

If the first tuple is greater than second tuple then it returns +1

Eg:

1. t1=(10,20,30)

2. t2=(40,50,60)

3. t3=(10,20,30)

4. print(cmp(t1,t2)) # -1

###### Tuple Packing and Unpacking:

We can create a tuple by packing a group of variables.

Eg:

a=10

b=20

t=a,b

print(t) #(10, 20)

Here a,b are packed into a tuple t. This is nothing but tuple packing.

Tuple unpacking is the reverse process of tuple packing

Ex:

1. t=(10,20,30)

2. a,b,c=t

3. print(“a=”,a,”b=”,b,”c=”,c)

4.

5. Output

6. a= 10 b= 20 c= 30

**Q. Write a
program to take a tuple of numbers from the keyboard and print its sum and average?**

t=eval(input(“Enter Tuple of Numbers:”))

l=len(t)

sum=0

for x in t:

sum=sum+x

print(“The Sum=”,sum)

print(“The Average=”,sum/l)

**Differences
between List and Tuple:**

**What is slicing?**

Slicing is a technique that allows us to retrieve only a part of a list, tuple, or string. For this, we use the slicing operator [].

>>> (1,2,3,4,5)[2:4]

**Are tuples immutable in python?**

Yes.

**Can we modify tuple element in python?**

No

Python tuple is an immutable object. Hence any operation that tries to update it is not allowed. However, we can perform this by below workaround.

First, convert tuple to list by built-in function list().

Update an item to list object assigning new value to element at certain index. Then use another built-in function tuple() to convert this list object back to tuple.

>>> T1=(1,2,3,4,5,6,7,8)

>>> L1=list(T1)

>>> L1[5]=10

>>> T1=tuple(L1)

>>> T1

(1,2,3,4,5,10,7,8)

**Extract unique tuples from list, Order Irrespective**

# initialize tuples list

test_list = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]

# printing original list

print(“The original list : ” + str(test_list))

# Extract unique tuples from list(Order Irrespective)

# using list comprehension + set()

res = set()

temp = [res.add((a, b)) for (a, b) in test_list

if (a, b) and (b, a) not in res]

# printing result

print(“The list after duplicated removal : ” + str(list(res)))

Output:

The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]

The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]

** Using ****frozenset()**

**frozenset()**

# initialize tuples list test_1 = [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)] # printing original list print(“The original list : ” + str(test_1)) # Extract unique tuples from list(Order Irrespective) # using frozenset() res = set(tuple(frozenset(sub)) for sub in set(test_1)) # printing result print(“The list after duplicated removal : ” + str(list(res))) |

**Output :**

The original list : [(1, 3), (4, 5), (3, 1), (1, 10), (5, 4)]

The list after duplicated removal : [(4, 5), (1, 3), (1, 10)]

**QUIZ:**

Interview questions:

**How to Convert string tuples to list tuples**

```
list1 = ["('ghfg', 1)", "('ihs', 2)"]
print("The original list : " + str(list1))
# Converting string tuples to list tuples
# using list comprehension + eval()
res1 = [eval(x) for x in list1]
print("The list tuple after conversion : " + str(res1))
--[('ghfg', 1), ('ihs', 2)]
```

###### How to find Find the tuples containing the given element from a list of tuples

```
listA = [('Mon', 2), ('Tue', 1)]
test = 'Mon'
res = list(filter(lambda x:test in x, listA))
```

what is singleton tuple in python

**When do you have to select LIST?**

Insertion order preserved.

Duplicate objects are allowed

Heterogeneous objects are allowed.

## Feedbacks & Improvements