Tuple

Tuple Data Structure

As we have studied in List in Java, we have Tuple in Python.

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.

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

6. 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)

Sort Tuples in Increasing Order by any key

Given a tuple, sort the list of tuples in increasing order by any key in tuple.

Input :  [(23, 45, 10), (25, 44, 20), (89, 40, 15)]

         m = 2

Output : Sorted: [(23, 45, 20), (89, 40, 23), (25, 44, 39)]

Explanation: Sorted using the 2nd index key

# get the last key.
def last(n): return n[m]      
# function to sort the tuple   
def sort(tuples):      
  # We pass used defined function last    
 # as a parameter.     
 return sorted(tuples, key = last)    
# driver code  
a = [(23, 45, 20), (25, 44, 39), (89, 40, 23)] m = 2 print(“Sorted:”), print(sort(a))

Output:

Sorted: [(23, 45, 10), (89, 40, 15), (25, 44, 20)]

 

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()

# 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)]

Interview questions:

How to Remove duplicate lists in tuples

How to Sort list of tuples by specific ordering

How to Count tuples occurrence in list of tuples

How to Remove tuples from list of tuples if greater than n

How to Convert string tuples to list tuples

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

what tuple in python

how create tuple in python

how to access tuple in python

how to sort tuple in python

how to print tuple in python

how to define tuple in python

how to split tuple in python

how to iterate tuple in python

how to append tuple in python

how to return tuple in python

how to update tuple in python

how to input tuple in python

how to delete tuple in python

how to call tuple in python

how to reverse tuple in python

what is singleton tuple in python

what is list tuple in python

what is tuple unpacking in python

what is tuple assignment in python

what is tuple object in python

what is tuple function in python

what is tuple error in python

when to use tuple in python