Hi Lucas.rs

You wrote:

> In its current implementation, the list type does not provide a simple and
> straightforward way to retrieve one of its elements that fits a certain
> criteria.
>

Thank you. You've asked a good question. I hope my answer will be helpful.

Here's my preferred solution, using Python builtins:
  >>> users = [
  ...     {'id': 1,'name': 'john'},
  ...     {'id': 2, 'name': 'anna'},
  ...     {'id': 3, 'name': 'bruce'},
  ... ]
  >>> func = (lambda user: user['id'] == 2)

  >>> next(filter(func, users))
  {'id': 2, 'name': 'anna'}

For comparison, here's your solution using your subclass of list.
  >> my_list.find(func)
   {'id': 2, 'name': 'anna'}

I prefer using the builtin filter function because:

1. I already know what 'filter' means.
2. I already know what 'next' means.
3. I already know what will happen if the object is not found (or if there
are several solutions.
4. It's fairly easy to modify the code to given different behaviour, eg
  >>> list(filter(func, users))
  [{'id': 2, 'name': 'anna'}]

Finally, perhaps your code would be better if the items in the 'user' list
were members of a class, rather than being bare dicts. And once you've done
that, you could create a new class for holding a collection (or set) of
members. And now we're moving towards how Django (and other frameworks)
handle interactions with a database.

-- 
Jonathan
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/KAMDP73KGFZQDYFBZVB7DZ44S5YDVJJD/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to