2

I'm a newbie. I am wondering if there is a way to easily find an instance of a class in a list with a given attribute. (Python)

basically the set up is as follows:


class idk:
    def __init__(self, name, num):
        self.name = name
        self.num = num

x = idk("x", 2)
y = idk("y", 3)
a = [x, y]

So a is a list with two instances of the class idk. How do I easily find the elements of a with name "x"?

I am looking for something like:

a["x"] returning x

or

b = [t in a, t.name == "x"] returning [x]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29

1 Answers1

1

You could use filter:

b = list(filter(lambda elem: elem.name == 'x', a))

but your list comprehension could work just fine as well.

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29