Search code examples
python-3.xlistslicecircular-list

Python - Create a new sublist between two elements in an ordered list


Given two elements in an ordered list, I want to make a new list consisting of everything between (and including) those elements. The problem comes if the second point comes before the first point in the list. right is my existing sorted list of objects. rt is the beginning boundary and rb is the end boundary. new_right = right[right.index(rt): right.index(rb) + 1]

This snippet works except in the case

right = [a, rb, c, rt, d, e]

where I get [rt, d, e] instead of the wrapped [rt, d, e, a, rb]

Is there a way to do this without creating a complicated method? Some other people's problems were solved by list comprehension. Looking into it, I was able to come up with

begin = right.index(rt)
end = right.index(rb)
if end > begin:
    new_right = right[begin: end + 1]
else:
    new_right = [right[i % r_len] for i in range(begin, r_len + end + 1)]

Which looks pretty ugly to me, but it seems to hold up to my tests. Is there a better way to do this?

EDIT: There were two working solutions to this.

rbegin = right.index(rt)
rend = right.index(rb)
if rend >= rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = [right[i % r_len] for i in range(rbegin, r_len + rend + 1)]

Which is obscenely complicated compared to:

if rend > rbegin:
    new_right = right[rbegin: rend + 1]
else:
    new_right = right[rbegin:] + right[:rend + 1]

Solution

  • Would simply flipping the slice match your tests like so:

    begin = right.index(rt)
    end = right.index(rb)
    if end > begin:
        new_right = right[begin: end + 1]
    else:
        new_right = right[end: begin + 1]