Lab 5: Python Tuples and Sets
Objectives:
The objectives for this lab are:
1. Understand Python tuples: creation, unpacking, and immutability,
2. Manipulate tuples: convert between tuples and other types, add items, compute
aggregates,
3. Explore Python sets: creation, basic operations (union, intersection, difference),
4. Apply loops and comprehension techniques to process tuples and sets.
Theory:
Tuples in Python are ordered, immutable collections that can store mixed data types.
Because they cannot be changed after creation, they’re often used for fixed groupings
of data (for example, coordinates or database records). You can convert tuples to
other types (string, list, dictionary) and use tuple unpacking to assign each element to
its own variable.
Sets are unordered collections of unique elements. They support mathematical set
operations like union (|), intersection (&), difference (-), and symmetric difference (^).
Sets are ideal when you want to eliminate duplicates or test membership quickly.
Both tuples and sets integrate smoothly with loops and comprehensions, letting you
transform, filter, and aggregate data with concise Python syntax.
Programs:
Tuples
1. Write a python program to convert a tuple to a string.
Code:
tup = (1, 2, 3, 4)
result = ' '.join(str(x) for x in tup)
print("Converted string:", result)
Output:
Converted string: 1234
2. Write a python program to get the 4th element from the last element of a tuple.
Code:
t = (10, 20, 30, 40, 50, 60, 70)
print(t[-4])
Output:
40
Anuska Shrestha, 800308
3. Write a Python program to find repeated items in a tuple.
Code:
t = (1, 2, 3, 2, 3, 4, 5, 6, 3)
repeats = tuple({x for x in t if [Link](x) > 1})
print(repeats)
Output:
(2, 3)
[Link] a Python program to replace the last value of tuples in a list.
Sample list: [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
Expected Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]
Code:
data = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
result = [t[:-1] + (100,) for t in data]
print(result)
Output:
[(10, 20, 100), (40, 50, 100), (70, 80, 100)]
5. Write a Python program to sort a tuple by its float element.
Sample data: [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
Expected Output: [('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
Code:
data = [('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]
sorted_data = sorted(data, key=lambda x: float(x[1]), reverse=True)
print(sorted_data)
Output:
[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]
6. Write a Python program to convert a given string list to a tuple.
Original string: python 3.0
<class 'str'>
Convert the said string to a tuple:
('p', 'y', 't', 'h', 'o', 'n', '3', '.', '0')
<class 'tuple'>
Code:
s = "python 3.0"
t = tuple(s)
print(t)
print(type(t))
Output:
('p', 'y', 't', 'h', 'o', 'n', ' ', '3', '.', '0')
<class 'tuple'>
Anuska Shrestha, 800308
7. Write a Python program to calculate the product, multiplying all the numbers
in a given tuple.
Code:
from functools import reduce
import operator
t1 = (4, 3, 2, 2, -1, 18)
t2 = (2, 4, 8, 8, 3, 2, 9)
product1 = reduce([Link], t1)
product2 = reduce([Link], t2)
print("Product:", product1)
print("Product:", product2)
Output:
Product: -864
Product: 27648
8. Write a Python program to calculate the average value of the numbers in a
given tuple of tuples.
Code:
t1 = ((10, 10, 10, 12), (30, 45, 56, 45), (81, 80, 39, 32), (1, 2, 3, 4))
averages1 = [sum(t)/len(t) for t in t1]
print(averages1)
t2 = ((1, 1, -5), (30, -15, 56), (81, -60, -39), (-10, 2, 3))
averages2 = [sum(t)/len(t) for t in t2]
print(averages2)
Output:
[10.5, 44.0, 58.0, 2.5]
[ -1.0, 23.67, -6.0, -1.67]
9. Write a Python program to convert a given tuple of positive integers into an
integer.
Code:
t1 = (1, 2, 3)
t2 = (10, 20, 40, 5, 70)
n1 = int(''.join(map(str, t1)))
n2 = int(''.join(map(str, t2)))
print(n1)
print(n2)
Output:
123
102040570
Anuska Shrestha, 800308
10. Write a Python program to compute the element-wise sum of given tuples.
Code:
t1 = (1, 2, 3, 4)
t2 = (3, 2, 1, 0)
t3 = (2, 2, 3, 1)
result = tuple(map(sum, zip(t1, t2, t3)))
print(result)
Output:
(6, 6, 7, 5)
11. Write a Python program to compute the sum of all the elements of each tuple
stored inside a list of tuples.
Code:
list1 = [(1, 2), (2, 3), (3, 4)]
sums1 = [sum(t) for t in list1]
print(sums1)
list2 = [(1, 2, 6), (2, 3, -6), (3, 4), (2, 2, 2, 2)]
sums2 = [sum(t) for t in list2]
print(sums2)
Output:
[3, 5, 7]
[9, -1, 7, 8]
Sets
12. Write a Python program to create an intersection, a union, set difference and
a symmetric difference of sets. Also find the length, maximum and minimum
values in a set.
Code:
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
print("Intersection:", set1 & set2)
print("Union:", set1 | set2)
print("Set Difference (set1 - set2):", set1 - set2)
print("Symmetric Difference:", set1 ^ set2)
print("Length of set1:", len(set1))
print("Max of set1:", max(set1))
print("Min of set1:", min(set1))
Anuska Shrestha, 800308
Output:
Intersection: {4, 5}
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Set Difference (set1 - set2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Length of set1: 5
Max of set1: 5
Min of set1: 1
13. Write a Python program that finds all pairs of elements in a list whose sum is
equal to a given value.
Code:
nums = [1, 2, 3, 4, 5, 6]
target_sum = 7
pairs = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target_sum:
[Link]((nums[i], nums[j]))
print("Pairs with sum", target_sum, ":", pairs)
Output:
Pairs with sum 7 : [(1, 6), (2, 5), (3, 4)]
14. Write a Python program to find the longest common prefix of all strings. Use
the Python set.
Code:
def longest_common_prefix(strings):
if not strings:
return ""
prefix = ""
for chars in zip(*strings):
if len(set(chars)) == 1:
prefix += chars[0]
else:
break
return prefix
strings = ["flower", "flow", "flight"]
print("Longest Common Prefix:", longest_common_prefix(strings))
Output:
Longest Common Prefix: fl
Anuska Shrestha, 800308
15. Write a Python program to find the two numbers whose product is maximum
among all the pairs in a given list of numbers. Use the Python set.
Code:
from itertools import combinations
nums = [1, 10, -5, 4, -6]
max_product = float('-inf')
max_pair = ()
for a, b in combinations(nums, 2):
product = a * b
if product > max_product:
max_product = product
max_pair = (a, b)
print("Max product pair:", max_pair)
print("Product:", max_product)
Output:
Max product pair: (-5, -6)
Product: 30
Conclusion:
In this lab we learnt how tuples are ordered collections of items that cannot be
changed once created. We can access their elements, slice them, and perform
operations like adding or multiplying the numbers inside. Sets, on the other hand, hold
unique items without order and are great for finding common or different elements
between groups. We also used sets to solve problems like finding pairs of numbers
with a specific sum or the longest shared prefix in words. Overall, tuples and sets help
organize and work with data efficiently in Python programs.
Anuska Shrestha, 800308