0

Is there a better way to code this?

def __contains__(self, e):
    return e in self.segments or True in [e in x for x in self.segments]

This function should return true if e is in self.segments or if e is in any of the segments in self.segments.

I'm still trying to learn how to use the [a for a in b if c] notations and I'm hoping that someone one StackOverflow can help me simplify that snippet.

Axoren
  • 623
  • 1
  • 8
  • 22

1 Answers1

4
def __contains__(self, e):
    return e in self.segments or any(e in x for x in self.segments)

any stops on the first element that evaluates to True and, without the square brackets, Python does not create an intermediary list.

Read about Generator Expressions vs. List Comprehension

Community
  • 1
  • 1
JBernardo
  • 32,262
  • 10
  • 90
  • 115