Feature Requests item #1548178, was opened at 2006-08-28 13:47 Message generated for change (Comment added) made by josiahcarlson You can respond by visiting: https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1548178&group_id=5470
Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: None Status: Open Resolution: None Priority: 4 Submitted By: kovan (kovan) Assigned to: Nobody/Anonymous (nobody) Summary: Add 'find' method to sequence types Initial Comment: In the benefit of Python's readability and simplicity, a 'find' method could be added to sequence types, that would return the first item in the list that matches some criteria. For example, it's a common practice to use lists of (key,value) pairs instead of dictionaries when the sequence must be ordered. To find an element maching a key in such cases, I frequently find myself writing (IMHO) too much code for such a straightforward operation. AFAIK currently there are two easy ways to do this (shouln't be one, and only one?): for item in items: if item.attribute == key: foundItem = item break else: foundItem = None OR foundItems = [item for item in items if item.key == value] if foundItems: foundItem = foundItem[0] IMO, in none of the cases the code is as clear and, specially, as short, as it should be. With the find method, the same code would be: item = items.find(lambda x: x.key == value) ---------------------------------------------------------------------- Comment By: Josiah Carlson (josiahcarlson) Date: 2006-09-03 12:07 Message: Logged In: YES user_id=341410 Lists have an .index(obj[, start[, stop]]) method that tells you the index of the first object that matches obj, raising an exception otherwise. Generally speaking, you can get better performance for repeated searches by... dct = {} for i,(k,v) in enumerate(lst): dct.setdefault(k, []).append(i) Then to find the first index... dct.get(k, [None])[0] Suggested close. ---------------------------------------------------------------------- You can respond by visiting: https://sourceforge.net/tracker/?func=detail&atid=355470&aid=1548178&group_id=5470 _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com