First matching item
When writing code one often needs to grab the first item in a collection that
has certain characteristics. For example, one may have a list of Student
objects and need to fetch the one with a certain id.
The task is trivial: loop through the list and compare each student's id until a match is found or all the students in the list have been inspected, whichever comes first.
In the past, I've tended to take advantage of return statements to exit the loop as soon as a match is found. The examples here are in Python, but the same patterns apply to other languages.
def student_by_id(students, id): for student in students: if student.id == id: return student return None
This appoach strikes me as inelegant when the function is called in one place only. Today a different approached occurred to me.
student = None for student in students: if student.id == id: break student = None
Here, we break out of the loop as soon as a match is found, preserving the
student of interest in the variable student. Each time through the loop
student is cleared to ensure that student is empty once we've finished
looping if there are no matches.
The first line is required to handle empty lists.
I think I'll use this approach from time to time. Let me know if you're aware of another option.
Possibly related posts
- Repeating strings in JavaScript
- Bitwise NOT operator proves useful in JavaScript
- Decorators in JavaScript
- Simulating
nonlocalin Python 2.x - Self-caching functions in JavaScript and Python
Comments
I prefer the predicate based approach:
students.first(_.id == id)
or
first(students, _.id == id)
cleaner and no looping.
Lee's comment on a similar post on Ryan Tomayko's blog is also worth a look. One of the options he proposes (for Python ≥ 2.6) reduces the code to a single line:
student = next((student for student in students if student.id == id), None)