Search code examples
pythonclassmethodsclass-method

Access item in class list


I'm trying to determine whether the first item in a tuple within a list exists in the assignments list using the following code.

class Students:
    id = int()
    full_name = ""
    assignments = [("Assign_1", 4), ("Assign_2", 10)]

    def __init__(self, id, full_name):
        self.id = int(id)
        self.full_name = full_name

    def get_name(self):
        print(self.full_name)
    def get_assignments(self):
        print(self.assignments)
    def get_assignment(self, name):
        if name in self.assignments:
            return name
        else:
            return None

Becky = Students(123, "Becky S")
Becky.get_assignments()
print(Becky.get_assignment("Assign_1"))

I've included more code than necessary just to illustrate the concept. When I use the get_assignments() method to return all assignments, I'm able to do so, but when I use get_assignment to print out the name of a single assignment, I keep returning None, as if the assignment doesn't exist. I think the issue is in how I'm defining get_assignment(self, name), but can't figure out what it is.


Solution

  • The problem here is not to do with classes. It is that you are trying to search for a string in a list of tuples.

    self.assignments is [("Assign_1", 4), ("Assign_2", 10)]. That is, each element in the list is a tuple of (name, id). When you do in, Python will compare the argument with each elemnt of the list. But "Assign_1" will never equal ("Assign_1", 4).

    Instead you would need to loop over the list and check if the name is in any of the elements:

    if any(assignment[0] == name for assignment in self.assignments)
    

    Note also, you have some issues with your understanding of Python classes. You don't want to define id or name at class level. Read this question for more.