user799825
user799825

Reputation: 39

How to know if an object is in a list of objects in python?

Suppose I have a list of Information objects:

list_users = [Information(name='Robert',  age=29), 
              Information(name='Richard', age=33),  
              Information(name='Carol',   age=43),  
              Information(name='Ann',     age=24)]

What is the easier way to know if a specific person is in the list based on his name?

I've been thinking if we could create magic methods but using lists in this way:

Robert in list_users: True

If is this impossible, someone could give me another idea?

Upvotes: 0

Views: 49

Answers (3)

Chris
Chris

Reputation: 36660

This is a great use for any and a generator expression.

if any(x.name == "Robert" for x in list_users):
    print("Robert is in the list")

Upvotes: 2

Chetan Goyal
Chetan Goyal

Reputation: 474

next((x for x in test_list if x.value == value), None)

This gets the first item from the list that matches the condition, and returns None if no item matches. It's my preferred single-expression form.

However,

for x in test_list:
    if x.value == value:
        print("i found it!")
        break

The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:

for x in test_list:
    if x.value == value:
        print("i found it!")
        break
else:
    x = None

This will assign None to x if you don't break out of the loop.

Upvotes: 0

sahasrara62
sahasrara62

Reputation: 11247

you can access name from the information object using obj.name

for user in list_users:
    if user.name = 'Robert':
        print("yes")
        break

Upvotes: 0

Related Questions