COL100 �Introduction to Computer Science
Lecture 18 – Tuples
February, 2025
Semester II
2024-2025
Vireshwar Kumar, Aaditeshwar Seth
CSE@IITD
Agenda
2
Disclaimer: The contents of these slides are taken from various publicly available resources such as books, talks and lectures. They are being used for the purpose of classroom teaching and academic dissemination only. The sources are acknowledged wherever possible.
Tuple
aTup = ("apple",5,"banana",3.2) print(aTup)
print(type(aTup))
print(len(aTup))
3
Indexing
aTup = ("apple",5,"banana",3.2) print(aTup[1])
print(aTup[-2])
print(aTup[1:3:1])
4
Immutability
aTup = ("apple",5,"banana",3.2)
aTuple[1] = "iitd-ad" # Error
5
Tuple Constructor
aTup = ("apple",5,"banana",3.2)
print(aTuple)
aList = [5, "iitd", 3.2]
print(aList)
aTuple = tuple(aList)
print(aTuple)
6
In-Built Methods
aTuple = (5, "iitd", 3.2)
print(len(aTuple))
7
Tuple Addition
aTuple = (5,"iitd",3.2)
bTuple = (2,6)
combinedTuple = aTuple + bTuple
print(combinedTuple)
8
Example: Swapping Variable Values
def quo_and_rem(x, y):
q = x // y
r = x % y
return (q, r)
(quo, rem) = quo_and_rem(42,5)
9
Working with Tuples
wordTuple = ("Apple", 3, 3.6)
for word in wordTuple:
print(type(word))
10
Tuples vs. Lists
names = ["aadi", "viresh", "amit", "riju", "maya", "tarun"]
marks_col100 = [100, 100, 80, 90, 75, 95]
marks_col106 = [50, 70, 100, 100, 80, 95]
marks_col334 = [93, 86, 63, 74, 76, 75]
marks_avg = [0] * 6
for i in range(0, 6):
marks_avg[i]=(marks_col100[i]+marks_col106[i]+marks_col334[i])/3
marks = [()] * 6
for i, name in enumerate(names):
marks[i]=(names[i],(marks_col100[i],marks_col106[i],marks_col334[i]),marks_avg[i])
print(marks, type(marks))
print(marks[2][1], type(marks[2][1]))
print(marks[2][1][2], type(marks[2][1][2]))
11
Call by value and call by reference
def remove(val, myList, dummystr, dummytuple):
for (i, val_at_i) in enumerate(myList):
if val == val_at_i and dummystr != "":
myList.pop(i)
val = -1
dummystr = "i protest, i am not a dummy string"
dummytuple = (3, 4, 5)
myList = [1, 4, 2, 4, 5, 6, 7]
val = 4
dummystr = "i am a dummy string"
dummytuple = (1, 2, 3)
print(myList, val, dummystr, dummytuple)
remove(val, myList, dummystr, dummytuple)
print(myList, val, dummystr, dummytuple)
12
Plot graphs
expr="x * x"
samples = [(x, eval(expr)) for x in range(-10, 11, 1)]
plt.plot([x for (x, y) in samples], [y for (x, y) in samples])
plt.show()
15
Additional examples
16