PYTHON - Tuple Exercises
Python Tuple Exercises
Python Tuple Exercise 1
Python program to find unique numbers in a given tuple −
PYTHON CODE
T1 = (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
T2 = ()
for x in T1:
if x not in T2:
T2+=(x,)
print ("original tuple:", T1)
print ("Unique numbers:", T2)It will produce the followingoutput−
PYTHON CODE
original tuple: (1, 9, 1, 6, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 2)
Unique numbers: (1, 9, 6, 3, 4, 5, 2, 7, 8)Python Tuple Exercise 2
Python program to find sum of all numbers in a tuple −
PYTHON CODE
T1 = (1, 9, 1, 6, 3, 4)
ttl = 0
for x in T1:
ttl+=x
print ("Sum of all numbers Using loop:", ttl)
ttl = sum(T1)
print ("Sum of all numbers sum() function:", ttl)It will produce the followingoutput−
PYTHON CODE
Sum of all numbers Using loop: 24
Sum of all numbers sum() function: 24Python Tuple Exercise 3
Python program to create a tuple of 5 random integers −
PYTHON CODE
import random
t1 = ()
for i in range(5):
x = random.randint(0, 100)
t1+=(x,)
print (t1)It will produce the followingoutput−
PYTHON CODE
(64, 21, 68, 6, 12)Exercise Programs
<ul class="list">
<li>pPython program to remove all duplicates numbers from a list.</li>
<li>pPython program to sort a tuple of strings on the number of alphabets in each word.</li>
<li>pPython program to prepare a tuple of non-numeric items from a given tuple.</li>
<li>pPython program to create a tuple of integers representing each character in a string</li>
<li>pPython program to find numbers common in two tuples.</li>
</ul>