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:
JavaScript
x
2
1
l = [True if a < x < b or c < x < d else False for x in range(n)]
2
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…
JavaScript
1
2
1
coordinates = [(a,b), (c,d), ]
2
…is there a way to still do this as a list comprehension? If not, what would be the most pythonic approach?
Advertisement
Answer
Yes, you can use a generator expression inside any
to accomplish this:
JavaScript
1
7
1
coordinates = [(2, 4), (3, 8)]
2
n = 5
3
4
l = [any(a < x < b for (a, b) in coordinates) for x in range(n)]
5
6
print(l)
7
Output:
JavaScript121[False, False, False, True, True]
2