May-15-2021, 07:14 PM
Searching and sorting collection or composite objects based one one of their attributes is a common programming problem. A dictionary would work better than tuples in this example, but what your items were personnel records and you wanted to find all employees who have worked for the company more than 10 years? Can you use a dictionary to do that? No, it would not. Sometime, eventually, you will need a way peek into an object and use that in your search or sort.
You could write a loop that looks at each tuple in the list, compares the employee name to the new contact name, and removes the tuple if they match. But what if you later wanted to search tuples to find a matching number (phone? ID?). That would require writing a different loop. A more realistic employee record might require dozens of different loops to handle all the possible searches.
A better method is to separate the comparison from the search. Can you think of a way where you could pass a function, maybe in the form of a lambda expression, as an argument to your search routine? Then you could have 1 search or that will work for searching any attribute. I mentioned sorting before because sorting has a feature like this. Maybe you can write your own "index" function that takes a "key" like the sort function?
You could write a loop that looks at each tuple in the list, compares the employee name to the new contact name, and removes the tuple if they match. But what if you later wanted to search tuples to find a matching number (phone? ID?). That would require writing a different loop. A more realistic employee record might require dozens of different loops to handle all the possible searches.
A better method is to separate the comparison from the search. Can you think of a way where you could pass a function, maybe in the form of a lambda expression, as an argument to your search routine? Then you could have 1 search or that will work for searching any attribute. I mentioned sorting before because sorting has a feature like this. Maybe you can write your own "index" function that takes a "key" like the sort function?