Search code examples
pythonlistinstances

Python get instance from list based on instance variable


Given a list of instances, say clients I'm trying to pluck an item from the list based on the value of a single instance variable screenName. I know I can do this:

for client in clients:
  if client.screenName = search:
    return client

But is there a nicer way of doing this without the loop?

Thanks for your help :)


Solution

  • You can use filter

    try:
        filter(lambda client: client.screenName == search, clients)[0]
    except IndexError:
        # handle error. May be use a default value