Alternative to list comprehension if there will be only one result

Viewed 17157

I'm starting to get used to list comprehension in Python but I'm afraid I'm using it somewhat improperly. I've run into a scenario a few times where I'm using list comprehension but immediately taking the first (and only) item from the list that is generated. Here is an example:

actor = [actor for actor in self.actors if actor.name==actorName][0]

(self.actors contains a list of objects and I'm trying to get to the one with a specific (string) name, which is in actorName.)

I'm trying to pull out the object from the list that matches the parameter I'm looking for. Is this method unreasonable? The dangling [0] makes me feel a bit insecure.

4 Answers
Related