Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare a value to a list of pairs in a list comprehension?

I need to create a list that is n long where each item is a Boolean. The item will only be True when x is in the range of one or more pairs of integers. For example, my current code is as follows:

l = [True if a < x < b or c < x < d else False for x in range(n)]

My issue is that the number of pairs will vary, so only a and b might exist in one instance, but e and f could also exist in another. If I were to structure my coordinate pairs in a list of tuples like so…

coordinates = [(a,b), (c,d), ...]

…is there a way to still do this as a list comprehension? If not, what would be the most pythonic approach?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, you can use a generator expression inside any to accomplish this:

coordinates = [(2, 4), (3, 8)]
n = 5

l = [any(a < x < b for (a, b) in coordinates) for x in range(n)]

print(l)

Output:

[False, False, False, True, True]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading