Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing items through a tuple in Python

Tags:

python

tuples

I am given an assignment when I am supposed to define a function that returns the second element of a tuple if the first element of a tuple matches with the argument of a function.

Specifically, let's say that I have a list of student registration numbers that goes by: particulars = (("S12345", "John"), ("S23456", "Max"), ("S34567", "Mary"))

And I have defined a function that is supposed to take in the argument of reg_num, such as "S12345", and return the name of the student in this case, "John". If the number does not match at all, I need to print "Not found" as a message. In essence, I understand that I need to sort through the larger tuple, and compare the first element [0] of each smaller tuple, then return the [1] entry of each smaller tuple. Here's what I have in mind:

def get_student_name(reg_num, particulars):
    for i in records:
        if reg_num == particulars[::1][0]:
            return particulars[i][1]
        else:
            print("Not found")

I know I'm wrong, but I can't tell why. I'm not well acquainted with how to sort through a tuple. Can anyone offer some advice, especially in syntax? Thank you very much!

like image 635
a9302c Avatar asked Mar 14 '26 06:03

a9302c


2 Answers

When you write for i in particulars, in each iteration i is an item of the collection and not an index. As such you cannot do particulars[i] (and there is no need - as you already have the item). In addition, remove the else statement so to not print for every item that doesn't match condition:

def get_student_name(reg_num, particulars):
    for i in particulars:
        if reg_num == i[0]:
            return i[1]
    print("Not found")

If you would want to iterate using indices you could do (but less nice):

for i in range(len(particulars)):
    if reg_num == particulars[i][0]:
        return particulars[i][1]
like image 172
Gilad Green Avatar answered Mar 16 '26 21:03

Gilad Green


Another approach, provided to help learn new tricks for manipulating python data structures:

You can turn you tuple of tuples:

particulars = (("S12345", "John"), ("S23456", "Max"), ("S34567", "Mary"))

into a dictionary:

>>> pdict = dict(particulars)
>>> pdict
{'S12345': 'John', 'S23456': 'Max', 'S34567': 'Mary'}

You can look up the value by supplying the key:

>>> r = 'S23456'
>>> dict(pdict)[r]
'Max'

The function:

def get_student_name(reg, s_data):
    try:
        return dict(s_data)[reg]
    except:
        return "Not Found"

The use of try ... except will catch errors and just return Not Found in the case where the reg is not in the tuple in the first place. It will also catch of the supplied tuple is not a series of PAIRS, and thus cannot be converted the way you expect.

You can read more about exceptions: the basics and the docs to learn how to respond differently to different types of error.

like image 38
NateB Avatar answered Mar 16 '26 22:03

NateB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!