Python: take an entry from a list of named tuples if contains particular attribute value

Viewed 1747

I have a list of namedtuples as below

fruits = Fruits['type', 'color', 'weight', 'sweetness']
f1 = fruits('apple', 'red', 1.89, 5)
f1 = fruits('pear', 'green', 2.89, 7)
f1 = fruits('banana', 'yellow', 2.01, 10)

l = [f1, f2, f3]

Now, I want to have a function which returns a particular namedtuple from the list given a type. I wrote this function using a for loop, but is it possible to do it better (faster or without for loop)?

def take_fruit(type, all_fruits):
    for f in all_fruits:
        if f.type == type:
           return f
    return None
2 Answers
Related