1

I'm newbie in python. I have this list for example:

[[1, 10],[11, 20],[21,30]]

Then I have a number 17. How can I find index by range. Number 17 is between 11 and 20. Index will be 1. I can do it with loop. Is there a way without loop by built in function?

3 Answers 3

2

This seems like the simplest way to do what you need to:

ranges = [[1, 10],[11, 20],[21,30]]
n = 17
for i, r in enumerate(ranges):
    if n in range(r[0], r[1]+1):
        print(i)
        break

Btw, for the kind of ranges you have, you can go for a more mathematical approach:

index = (n-1) // 10
Sign up to request clarification or add additional context in comments.

1 Comment

Thx for a quick answer
1

You can use filter combined with next:

ranges = [[1, 10],[11, 20],[21,30]]
target = 17

target_range = next(filter(lambda range: range[0] < target < range[1], ranges))

target_range will be [11, 20] in this case.

filter here is responsible for excluding ranges that do not have target within them. And assuming that the ranges do not overlap, filter will exclude every range but one, and we can get that one with next.

You can also change up the criteria for what ranges are kept. If you consider 11 part of [11, 20] (right on the border), you can do range[0] <= target <= range[1] instead.

2 Comments

Not sure if this will be suitable for a "newbie" in python but good answer :)
Thx for a quick answer
1

You could use generator expression.

>>> def find_index_by_range(*, collection, target):
...     return next(
...         (index for index, value in enumerate(collection) if target in range(*value)),
...         None,
...     )
...

>>> ranges = [[1, 10],[11, 20],[21,30]]
>>> find_index_by_range(collection=ranges, target=17)
1
>>> find_index_by_range(collection=ranges, target=28)
2

1 Comment

Thx for a quick answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.