On Sat, 7 May 2022 at 16:42, <python-ideas@lucas.rs> 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.
If you had to get the user where user['id'] == 2 from this list of users, for example, how would you do it?
users = [ {'id': 1,'name': 'john'}, {'id': 2, 'name': 'anna'}, {'id': 3, 'name': 'bruce'}, ]
# way too verbose and not pythonic ids = [user['id'] for user in users] index = ids.index(2) user_2 = users[index]
# short, but it feels a bit janky user_2 = next((user for user in users if user['id'] == 2), None)
# this is okay-ish, i guess users_dict = {user['id']: user for user in users} user_2 = users_dict.get(2)
In my opinion, the list type could have something along these lines:
class MyList(list): def find(self, func, default=None): for i in self: if func(i): return i return default
my_list = MyList(users) user_2 = my_list.find(lambda user: user['id'] == 2) print(user_2) # {'id': 2, 'name': 'anna'}
You seem to want a function, but it's not obvious to me why you need that. found = None for user in users: if user["id"] == 2: found = user break seems fine to me. If you need a function def find_user(id): for user in users: if user["id"] == id: return user works fine. Python is very much a procedural language, and "simple and straightforward" often equates to a few statements, or a loop, or similar. Unlike functional languages, where people tend to think of "simple" code as being about combining basic functions into compound expressions that do "clever stuff", Python code tends to be viewed as "simple and straightforward" (or "Pythonic" if you like) if it *doesn't* try to combine too much into one expression, but describes what you're doing in a step by step manner. So yes, a list doesn't provide the sort of "find" method you're suggesting. That's because a loop is easy, and does the job just fine. Paul