Skip to content
Advertisement

Finding all the elements in a list between two elements (not using index, and with wrap around)

I’m trying to figure out a way to find all the elements that appear between two list elements (inclusive) – but to do it without reference to position, and instead with reference to the elements themselves. It’s easier to explain with code:

I have a list like this:

['a','b','c','d','e']

And I want a function that would take, two arguments corresponding to elements eg. f('a','d'), and return the following:

['a','b','c','d']

I’d also like it to wrap around, eg. f('d','b'):

['d','e','a','b']

I’m not sure how to go about coding this. One hacky way I’ve thought of is duplicating the list in question (['a','b','c','d','e','a','b','c','d','e']) and then looping through it and flagging when the first element appears and when the last element does and then discarding the rest – but it seems like there would be a better way. Any suggestions?

Advertisement

Answer

def foo(a, b):
    s, e = [a.index(x) for x in b]
    if s <= e:
        return a[s:e+1]
    else:
        return a[s:] + a[:e+1]

print(foo(['a','b','c','d','e'], ['a', 'd']))  # --> ['a', 'b', 'c', 'd']

print(foo(['a','b','c','d','e'], ['d', 'b']))  # --> ['d', 'e', 'a', 'b']
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement