0

Extract items from the list with comes in between another list items

a = [4,8]
b = [1,2,3,4,5,6,7,8,9,0]

I want to extract values from b list which comes in between 4 and 8 values of list a ?

Result should be

b = [5,6,7]
3
  • 1
    a always have 2 values only? Commented May 28, 2019 at 8:04
  • 1
    You might want to add another example. when you say comes in between, are you using 4 and 8 as "indexes" or "values"? For a better example, given b = [10,20,25,30] can a be [23, 27] or a will be [1,3]? Commented May 28, 2019 at 8:06
  • yes ....list a will always have 2 values Commented May 28, 2019 at 8:06

3 Answers 3

2

You can use inbuilt filter() method.

a = [4, 8]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# If you aren't sure that items in a is in correct order then use min max
c = list(filter(lambda x: min(a) < x < max(a), b))

Or use list comprehension:

c = [x for x in b if min(a) < x < max(a)]
Sign up to request clarification or add additional context in comments.

Comments

1
In [8]: a = [4,8]

In [9]: b = [1,2,3,4,5,6,7,8,9,0]

In [10]: [ item for item in b if a[0] < item < a[1]]
Out[10]: [5, 6, 7]

1 Comment

You could directly use a[0] < item < a[1]
0

Others have posted answers that rely on ordered lists of integers. However, if you are operating on unordered lists where values can be of any type, this answer will work where others do not.

result = b[b.index(a[0]) + 1 : b.index(a[1])]
In[2]: a = [1, "a"]; b = [0.229, "b", 1, [], "c", 5, "5", 2, "a"]
In[3]: b[b.index(a[0]) + 1 : b.index(a[1])]
Out[4]: [[], 'c', 5, '5', 2]

Comments

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.